Friday, October 31, 2014

Re: Primary keys vs. natural keys

Hi Torsten,

> On Oct 31, 2014, at 3:13 AM, Torsten Bronger <bronger@physik.rwth-aachen.de> wrote:
> Do I understand it correctly that in the Django community, it is
> preferred to use surrogate primary keys (the auto ID field) instead
> of explicitly setting primary keys?

Yes, I'd say this is true.

> Currently, I add natural_key()
> methods to many of my models, but some of them return only one
> field. Now I wonder whether I made a mistake and should have chosen
> that field as the primary key.
>
> My use case is that I need to retrieve the natural keys of all
> objects in the database of a particular model. As far as I can see,
> this can only be achieved by fetching all objects and calling the
> natural_key() method for all of them. In contrast,
>
> model.objects.values_list("pk", flat=True)
>
> is probably *much* faster.
>
> Is it possibly to specify a single field a natural key somehow
> (besides making it the PK)? For example, it is possible to add a
> Meta attribute to the model?

There is no built in feature for this, but it doesn't seem like a hard problem to solve with your own conventions. For instance, rather than hardcoding the name of the natural key field inside the natural_key method, make it a model class attribute, e.g. MyModel.natural_key_field. Then the natural_key method can return getattr(self, self.natural_key_field) (you could even implement this method just once in an abstract base or mixin), and you can also use the attribute to do your efficient query: MyModel.objects.values_list(MyModel.natural_key_field, flat=True)

There may be reasons to consider natural primary keys in your data model (though personally I think surrogates are usually a better choice), but I don't think the problem you presented implies that you made the wrong choice.

Carl

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7EC7C040-056D-422F-BE10-0707F72F230C%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment