Peewee: Allow for using PEP8 compliant comparisons in boolean Fields

Created on 30 May 2015  路  4Comments  路  Source: coleifer/peewee

Current implementation necessitates this sort of syntax:

     Model.selec().where(Model.field == True)

This raises a E712 comparison to True should be 'if cond is True:' or 'if cond:' and similarly with comparisons to False.

Would be nice to be able to do:

         Model.selec().where(Model.field is True)

or even perhaps:

         Model.selec().where(not Model.deleted)

Most helpful comment

@coleifer Would adding something like .equals(value) or .bool(value) (to http://docs.peewee-orm.com/en/latest/peewee/querying.html#query-operators) be out of the question?

All 4 comments

There is no way to override the is lookup, so this won't work. Same thing for not, and and or.

@coleifer Would adding something like .equals(value) or .bool(value) (to http://docs.peewee-orm.com/en/latest/peewee/querying.html#query-operators) be out of the question?

I came across this issue because autopep8 was breaking my queries to be pep8 compliant. For instance, my original query

profile_image = Image.select().where(
    (Image.organization == org_id) &
    (Image.user == None) &
    (Image.id == image_id)
).get()

was having its == None replaced with is None, becoming

profile_image = Image.select().where(
    (Image.organization == org_id) &
    (Image.user is None) &
    (Image.id == image_id)
).get()

which led to a peewee.DoesNotExist error. I'm not sure if something like @tuukkamustonen's suggestion was ever implemented (I didn't find it), but an alternative would be to define a constant like

peewee.NULL = None

so comparison to null values can be compared with == in a pep8 compliant way.

For instance,

profile_image = Image.select().where(
    (Image.organization == org_id) &
    (Image.user == peewee.NULL) &
    (Image.id == image_id)
).get()

Update: use @coleifer's solution below.

To do null testing, use:

Image.user.is_null(True)

Or

Image.user.is_null(False)  # IS NOT NULL

Which is important because IS NOT NULL has different semantics than NOT (... IS NULL).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alexlatchford picture alexlatchford  路  4Comments

hanxifu picture hanxifu  路  4Comments

razodactyl picture razodactyl  路  3Comments

mmongeon-aa picture mmongeon-aa  路  4Comments

rayzorben picture rayzorben  路  4Comments