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:
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
Most helpful comment
As the documentation states, when using a non-auto-incrementing primary key, you must call
save()on new instances by passingforce_insert=True.http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks