[英]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. 我想
University
有很多Departments
,反之亦然,这很好。 But I also want to store more departments individually for one university. 但是我也想为一所大学单独存储更多的系。
For instance: 例如:
University1 has Department1 and Department2. University1有Department1和Department2。
University2 has Department1. University2有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.
现在,当我更新Department1时,当然拥有该学校的每所大学都会发生变化。 I don't want that.
我不要 I want to update Department1 but only for the University1 record.
我想更新Department1,但只更新University1记录。 Department1 in University2 shouldn't be updated.
University2中的Department1不应更新。
I assume that adding through
option with intermediate model
wouldn't help. 我以为中间
model
添加through
选项无济于事。 What's the best solution? 最好的解决方案是什么?
For the first part of your question 对于您问题的第一部分
But I also want to store more departments individually for one university.
For the second part of your question 对于您问题的第二部分
I want to update Department1 but only for the University1 record.
我想更新Department1,但只更新University1记录。 Department1 in University2 shouldn't be updated
University2中的Department1不应更新
So if you want to update Department 1 for all universities you update Department 1's instance. 因此,如果要为所有大学更新部门1,则需要更新部门1的实例。
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. 如果只想用部门1和大学1之间的唯一内容更新部门1,则将在两个模型之间的穿透表中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.