3

Is there a meaningful difference between

if self.pk is not None:

and

if self.pk:

when checking a model field in python django?

Other languages have all kinds of differing 'correct' ways to check for a variable being null, empty, nonexistant, whatever.

a) I don't know how python handles the check

b) I don't know if this is important and / or meaningful in the context of django model fields

Illumin8s
  • 121
  • 1
  • 8

2 Answers2

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
  • 5,583
  • 8
  • 39
  • 41
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.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83