Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queries - id vs pk

People also ask

What is PK in Django?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".

What is id in Django?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.

Does Django automatically create ID?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

What is primary key in Django model?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).


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.


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.