我将中间模型用于“ManyToManyField using the through”
通常,如果我不使用中间字段,则 m2m 关系将是唯一的,并且不能有重复的数据。
在我使用中间模型之后。 m2m 之间的关系可以有相同的数据。像这样
| | ['0'] (
| | | addToProfile => Array (0)
| | | (
| | | )
| | | endDate = NULL
| | | feedType = "N"
| | | id = 1
| | | info = "Big Kuy No Fear"
| | | likeMaker => Array (3)
| | | (
| | | | ['0'] = "/api/v2/user/2/"
| | | | ['1'] = "/api/v2/user/2/"
| | | | ['2'] = "/api/v2/user/2/"
| | | )
| | | like_count = "3"
我正在建立一个社交网络。所以这是我的提要对象,它有 3 个 like_count s。但是这三个像来自同一个用户“/api/v2/user/2/”
我尝试在 m2m 字段中添加“unique=True”属性,但是 django 出现了错误,因为它首先没有授予将“unique”属性添加到 m2m 字段的权限。谁能帮我
最佳答案
尝试在中间模型中使用 unique_together 。
class M2MModel(models.Model):
field1 = models.ForeignKey(Model1)
field2 = models.ForeignKey(Model2)
class Meta:
unique_together = ('field1', 'field2')
关于django - 当我使用中间模型时,多对多关系并不是唯一的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753654/