Multiple fields primary keys in Django

I’m developing a little application in Django.

Having developed a subtle dislike for UUIDs used as primary keys I tend to rely of the “natural keys” which are almost always identificable in a data model.

Often thought those keys span over several fields. Think about a receipt of a multi-store multi-cashier store, their receipts are identificable by the tupla <store_id, cashier_id, date, progressive_number>.

It seems that Django currently does not allow, at least out-of-the-box to use several fields grouped into a tuple as primary key. It’s also explained in its FAQs:


Do Django models support multiple-column primary keys?
No. Only single-column primary keys are supported.
But this isn’t an issue in practice, because there’s nothing stopping you from adding other constraints (using the unique_together model option or creating the constraint directly in your database), and enforcing the uniqueness at that level. Single-column primary keys are needed for things such as the admin interface to work; e.g., you need a simple way of being able to specify an object to edit or delete.

So I understand why lazy developers use UUIDs.

Simone Federici has written django-compositekey but AFAICS it support only Django 1.x and not the current 2.x
It seems I have to maintain uniqueness django-way and I don’t like it the way it is: it looks like an ugly kludge.

Update:

I’ve been busy with completely unrelated issues but I still haven’t solved this. Apparently neither Django developers as they wrote in “Multi-Column Primary Key support“. Too bad, I’ll make up those keys composing primary key strings like "$store_id-$cashier_id-YYYY-MM-DD-$progressive_number". Hoping that my little hack will not still be in use in year ten thousand

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.