How to remove redundant ID field in auto-generated ManyToMany table in Django?

别等时光非礼了梦想. 提交于 2019-12-07 06:30:38

问题


I have two classes in my models.py file:

class Person:
    person_name = models.CharField(max_length = 50)

class Course:
    course_name = models.CharField(max_length = 50)
    course_person = models.ManyToManyField(Person)

In my modified example, one person is takes many courses and one course is taken by many people, hence ManyToMany.

When I let Django auto-generate my table, I get an extra ID field. I want the autogenerated person_course manytomany table to consist of the two composite keys person_id and course_id only. Note: Both of them are auto-generated, auto-incremented fields.

I have also tried defining my ManyToMany class and attempted to link the fields using the keyword through=, but that did not help.

I have asked Google but without much help. Many some geniuses among you can provide some hint :)


回答1:


Django currently does not support composite primary key by default

What you can do instead is keep the auto generated id as the (surrogate) primary key and then define a unique_together relationship in the through table.

class Meta:
    unique_together = (course, person)

This way, you can guarantee unique entries in the through table, and when you reference the id it is the equivalent of referencing the unique (course, person) which is what we want anyways.

There are some third party apps that implement this feature if you want. However, unless an absolute necessity (like a legacy system support), I would just keep it simple and implement unique_together.



来源:https://stackoverflow.com/questions/17365883/how-to-remove-redundant-id-field-in-auto-generated-manytomany-table-in-django

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