Django queries - id vs pk

霸气de小男生 提交于 2019-11-26 21:41:32

It doesn't matter. pk is more independent from the actual primary key field i.e. you don't have to care whether the primary key field is called id or object_id or whatever.

It also gives your more consistency if you have models with different primary key fields.

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 microsecond is nothing for web.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!