Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 406
Shailen Avatar asked Jun 28 '13 13:06

Shailen


1 Answers

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.

like image 154
karthikr Avatar answered Nov 15 '22 04:11

karthikr