How to set 2 attributes to primary key together in Django?

十年热恋 提交于 2021-02-09 11:01:11

问题


I have a model in Django:

 class Subject(models.Model):
    level = models.CharField(max_length=50)
    subject_name = models.CharField(max_length=50)
    teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    total_seats = models.IntegerField()
    subject_details = models.CharField(max_length=50)

For the Subject table I want the level and the subject_name together to be primary keys. In fact, I dont want any other objects to have the same name and level. I know I can use unique_together but where do I mention the primary_key = True?


回答1:


You don't. Django does not work with composite primary keys. This is specified in the documentation:

Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

In the FAQ section it also continues with:

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 single value to specify an object to edit or delete.

It is a feature that is often requested (see for example this Django ticket), but it was not implemented. It will probably be quite cumbersome, first of all a lot of existing Django tooling will need to be updated (for example JOINs should be done with the two keys, FOREIGN KEYs should then result in two or more fields constructed, etc.). But another, and probably even more severe problem might be the large number of packages built on top of Django that make the assumption that the primary key is not a composite. It would thus break a lot of packages in the Django "ecosystem".

There are some packages like django-compositekey [GitHub] that aim to implement this. But the last update is made in october 2014.

It is not per se a problem not to make it a primary key. In fact Django's GenericForeignKey [Django-doc] only works if the primary keys are all of the same type. So using unique_together should be sufficient. Normally this will also make a UNIQUE INDEX at the databaes side.




回答2:


I think you want this 2 fields indexed by database because the main cause of primary key is to make field unique and indexed by the DBMS, so you can make your fields unique_together in Meta class and set db_index=True in field args.



来源:https://stackoverflow.com/questions/61320317/how-to-set-2-attributes-to-primary-key-together-in-django

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