280👍
It doesn’t matter. pk
is more independent from the actual primary key field i.e. you don’t need to care whether the primary key field is called id
or object_id
or whatever.
It also provides more consistency if you have models with different primary key fields.
68👍
In Django projects where I know that pk
always returns id
I prefer using id
when it does not clash with the id()
function (everywhere except variable names). The reason for this is that pk
is a property which is 7 times slower than id
since it takes time looking up pk
attribute name in meta
.
%timeit obj.id
46 ns ± 0.187 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit obj.pk
347 ns ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Here is the relevant Django code:
def _get_pk_val(self, meta=None):
meta = meta or self._meta
return getattr(self, meta.pk.attname)
def _set_pk_val(self, value):
return setattr(self, self._meta.pk.attname, value)
pk = property(_get_pk_val, _set_pk_val)
It is really a rare case when I need to use a variable named pk
. I prefer using something more verbose, like user_id
instead of pk
.
Following the same convention is preferable across the whole project. In your case id
is a parameter name, not a property, so there is almost no difference in timings. Parameter names do not clash with the name of built-in id()
function, so it is safe to use id
here.
To sum up, it is up to you to choose whether to use field name id
or the pk
shortcut. If you are not developing a library for Django and use automatic primary key fields for all models, it is safe to use id
everywhere, which is sometimes faster. From the other hand, if you want universal access to (probably custom) primary key fields, then use pk
everywhere. A third of a microsecond is nothing for web.
- [Django]-Django MEDIA_URL and MEDIA_ROOT
- [Django]-Django dynamic forms – on-the-fly field population?
- [Django]-What is the difference between cached_property in Django vs. Python's functools?