Django ManyToMany Field Through With Extra Fields Does Not Show On Both Relations
Solution 1:
I think you need to specify the through_fields
argument to your ManyToManyField
.
When Django autogenerates your through model, it knows which of the two ForeignKey
s in it corresponds to the "local" end of the relationship, and which is the "remote" end. However, when you specify a custom intermediary model, this makes it more difficult. It is possible that Django just takes the first ForeignKey
in the intermediary model pointing to the right target model, which in both cases happens to be source
here (although I'm not sure this is really the case, and if it is, it might be a bug).
Try to see if using through_fields=('source', 'destination')
helps.
Solution 2:
Following up on the @koniiiik's answer regarding through_fields
:
Recursive relationships using an intermediary model are always defined as non-symmetrical – that is, with
symmetrical=False
– therefore, there is the concept of a“source”
and a“target”
. In that case'field1'
will be treated as the“source”
of the relationship and'field2'
as the“target”
.
and, in your case it is source
and destination
.
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
if you add a connection:
Connection(source=A, destination=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
Post a Comment for "Django ManyToMany Field Through With Extra Fields Does Not Show On Both Relations"