Peewee: .save() doesn't work when primary key is manually assigned

Created on 24 Nov 2014  路  2Comments  路  Source: coleifer/peewee

Hello,

I have a model that looks something like this:

class Page(Model):
    class Meta:
        database = PostgresqlDatabase('example')
    url = CharField(primary_key=True)
    content = TextField()

If I manually create a Page instance, call .save() and then immediately query for that instance, I get a DoesntExist exception:

URL = 'http://example.com'

page = Page(
    url=URL
)

page.content = 'whatever'
page.save()

Page.get(Page.url == URL)  # raises peewee.PageDoesNotExist

What's going on?

Here's a full test script which reproduces the problem:

from peewee import *  # noqa
from playhouse.postgres_ext import *  # noqa

db = PostgresqlDatabase('example')


class Page(Model):
    class Meta:
        database = db
    url = CharField(primary_key=True)
    content = TextField()


def init():
    try:
        Page.drop_table()
    except ProgrammingError:
        db.rollback()

    Page.create_table()


init()

URL = 'http://example.com'

page = Page(
    url=URL
)

page.content = 'whatever'
page.save()

Page.get(Page.url == URL)

Details:

  • Peewee 2.4.3
  • psycopg2 2.5.4
  • Python 3.4.1
  • PostgreSQL 9.3.5
  • OSX 10.10.1

Most helpful comment

As the documentation states, when using a non-auto-incrementing primary key, you must call save() on new instances by passing force_insert=True.

http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks

All 2 comments

After looking at how the save() method is implemented, it looks like it can't tell the difference between this:

page = Page.get(Page.url == 'http://example.com')

and this:

page = Page(url='http://example.com')

i.e. between a persisted object and one that exists only in Python.

Anyway, my workaround was to add an extra if and use Page.create().

I'll leave this open in case it's deemed worth fixing.

As the documentation states, when using a non-auto-incrementing primary key, you must call save() on new instances by passing force_insert=True.

http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hanxifu picture hanxifu  路  4Comments

lucasrc picture lucasrc  路  5Comments

ghost picture ghost  路  5Comments

alexpantyukhin picture alexpantyukhin  路  5Comments

megachweng picture megachweng  路  3Comments