问题描述
我有一堂课 Assembly
class Assembly(models.Model):
room = models.ForeignKey("Room", related_name="assemblies")
name = models.CharField(max_length=200)
number = models.IntegerField()
position = models.CharField(max_length=200, blank=True)
components = models.ManyToManyField("material.Component", through="m2m_Assembly_Components")
connections = models.ManyToManyField("Assembly", through="Connection")
category = models.ForeignKey("Category", default=0)
notes = models.TextField(blank=True)
在其实例(连接
)之间具有ManyToMany Realtionship.我使用中间表 Connection
,这样我可以在 Assembly
的两个实例之间建立用于连接的其他字段.
that has a ManyToMany Realtionship between instances of itself (connections
).I use an intermediary table Connection
so that i can have additional fields for a connection between two instances of an Assembly
.
class Connection(models.Model):
source = models.ForeignKey("Assembly", related_name="source_assembly", null=True)
destination = models.ForeignKey("Assembly", related_name="destination_assembly", null=True)
length = models.IntegerField(null=True, blank=True)
如果我有两个程序集,比如说A和B,然后通过定义一个新的Connection(使用A作为源,B作为目标)来连接它们,我将B作为A的连接( A.connections.all()
),但我没有得到A作为B的连接.
If I have two Assemblies, lets say A and B, and I connect them by defining a new Connection with A as source and B as destination, I get B as A's connections (A.connections.all()
), but I don't get A as B's connections.
如果我不使用中间表,只需一个 models.ManyToManyField("Assembly")
我将A作为B的连接并将B作为A的连接.
If I don't use an intermediary table, just a models.ManyToManyField("Assembly")
I get A as B's connections and B as A's connections.
我这是什么问题?
推荐答案
关注有关 through_fields
:
,在您的情况下,它是 source
和 destination
.
and, in your case it is source
and destination
.
由于您正在使用中介模型 Connection
,因此该关系不再对称.因此, A.connections.all()
和 B.connections.all()
将返回不同的结果.
Since you are using an intermediary model Connection
, the relationship is not symmetrical anymore. Therefore, A.connections.all()
and B.connections.all()
will return different results.
A.connections.all() #all assemblies where A is source
B.connections.all() # all assemblies where B is source
如果添加连接:
Connection(source=A, destination=B)
您可以使用以下命令找到所有以B为目标的程序集:
you can find all the assemblies where B is destination using:
B.destination_assembly.all().values_list('source', flat=True) # this will include A
这篇关于带有额外字段的Django ManyToMany字段在两种关系中均不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!