[Django]-Django model field: Checking "if field is not None" vs. "if field"

5đź‘Ť

âś…

The first check is checking that the primary key is not None. The second is checking that the primary key is truthy. So yes, there is a difference.

👤Celeo

1đź‘Ť

Pk is a property that usually resolves to id. There is no magic other than that.

So the only difference between the two statements is how Python treats them. The first one explicitely tests if pk is None, whereas the second one will pass for any “falsy” value of pk.

Note that pk shouldn’t usually evaluate to False unless the model instance is not saved to the database, so in practice the two statements should be pretty much equivalent.

Leave a comment