What is the difference between django pk and id and how to use?

created at 07-17-2021 views: 2

Introduction

If not explicitly specified, by default id is the name of the field created as the primary key.

And pk is independent of the actual primary key. That is, you don't need to care about whether the primary key field is called id or user_id or whatever. Using pk can improve the consistency of the code.

When a table has models with different primary key fields, id is more useful.

In fact, there is no difference between id and pk for most tables, but pk is recommended.

speed of id and pk

%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)

After testing, it is found that using id is indeed faster than pk. This is because meta is looking for events that need to be spent on pk attributes. But please note that the unit is nanoseconds.

pk related code in django

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)

In the network request, the use of pk will consume one-third of the microsecond time, which can be ignored.

in conclusion: there is no difference between id and pk.

Please log in to leave a comment.