Django多个多对多通过

时间:2022-02-16 20:16:21

I have two models A and B with an intermediary model C for holding a many-to-many relation using the through. as extra fields in C can have different values for the two same related objects of A and B, is it logically OK to do that? i.e. pair of foreign keys to (A, B) in C to be not unique (Django do not create unique_together on them)

我有两个模型A和B,中间模型C用于通过直通保持多对多关系。因为C中的额外字段对于A和B的两个相同的相关对象可以具有不同的值,所以在逻辑上可以这样做吗?即C中(A,B)的外键对不是唯一的(Django不会在它们上创建unique_together)

1 个解决方案

#1


1  

It is possible for multiple relationships between two objects to exist in your through table. This can have surprising results when fetching related items, however, as a.b_set.all() will contain multiple copies of the item from B where there are multiple relationships. If this is not desired, then you can use a.b_set.all().distinct() to remove the duplicate items.

两个对象之间的多个关系可能存在于直通表中。但是,当获取相关项时,这会产生令人惊讶的结果,因为a.b_set.all()将包含来自B的项目的多个副本,其中存在多个关系。如果不需要,则可以使用a.b_set.all()。distinct()删除重复项。

#1


1  

It is possible for multiple relationships between two objects to exist in your through table. This can have surprising results when fetching related items, however, as a.b_set.all() will contain multiple copies of the item from B where there are multiple relationships. If this is not desired, then you can use a.b_set.all().distinct() to remove the duplicate items.

两个对象之间的多个关系可能存在于直通表中。但是,当获取相关项时,这会产生令人惊讶的结果,因为a.b_set.all()将包含来自B的项目的多个副本,其中存在多个关系。如果不需要,则可以使用a.b_set.all()。distinct()删除重复项。