简体   繁体   中英

ManyToMany models relationship Django

I have two models:

class University(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=50, null=True, blank=True)
    city = models.CharField(max_length=30, null=True, blank=True)
    country = CountryField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
    departments = models.ManyToManyField(Department)


class Department(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=50, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

I want to University have many Departments and vice versa which works fine. But I also want to store more departments individually for one university.

For instance:

University1 has Department1 and Department2.

University2 has Department1.

I want those departments store individually for each university. Now when I update Department1, ofcourse every University which has that school will see changes. I don't want that. I want to update Department1 but only for the University1 record. Department1 in University2 shouldn't be updated.

I assume that adding through option with intermediate model wouldn't help. What's the best solution?

For the first part of your question

But I also want to store more departments individually for one university.
  • You can crate the departments and only add them to the university you want them to have a relationship with.

For the second part of your question

I want to update Department1 but only for the University1 record. Department1 in University2 shouldn't be updated

  • You should add through tables. A through table defines the relationship between two models and it's purpose is to store what is unique to each specific relationship.

So if you want to update Department 1 for all universities you update Department 1's instance.

If you want to only update Department 1 with something unique between Department 1 and University 1, that goes in the through table between the two models.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM