问题
I don't understand how to follow many-to-many relations in the reverse direction with django-gm2m. Here is an example of an models.py:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from gm2m import GM2MField
class A(models.Model):
pass
class B(models.Model):
pass
class X(models.Model):
things = GM2MField()
class Y(models.Model):
things = GM2MField(through='Yrel')
class Yrel(models.Model):
y = models.ForeignKey(Y)
thing = GenericForeignKey(ct_field='thing_ct', fk_field='thing_fk')
thing_ct = models.ForeignKey(ContentType)
thing_fk = models.CharField(max_length=255)
timestamp = models.DateTimeField(auto_now_add=True)
X and Y both have "things" which contains several arbitrary objects. It is Y I have problems with, and X is only for comparison.
I have a few objects to test with.
a1, a2, b1 = A(), A(), B()
a1.save()
a2.save()
b1.save()
etc. With the class X I can do
x1, x2 = X(), X()
x1.save()
x2.save()
x1.things.add(a1, b1)
x2.things.add(a1)
and then get the added things back with x1.things.all()
etc. To go in the reverse direction I use x_set
as in a1.x_set.count()
.
So far so good. With "Y" that uses "through" I do
y1 = Y()
y1.save()
Yrel(y=y1, thing=a1).save()
Yrel(y=y1, thing=a2).save()
to add two "things", and then I can get the list back with y1.things.all()
again. But how can I do a reverse lookup from a1
to see where it is used?
回答1:
As described in the documentation django-gm2m can only create the related reverse relation after you have added an instance to the *_set
(as you did with the X
objects), as it can't know on which models the reverse relation is needed.
If you would like to access the reverse relations without having added something before you need to specify on which models they should get created:
class Y(models.Model):
things = GM2MField(through='Yrel', A, B)
This somehow resembles Django's behaviour where you would also have to create the reverse relation for GenericForeignKey
manually.
来源:https://stackoverflow.com/questions/54768568/reverse-relations-with-django-gm2m-using-through-relation