使用“直通"与django-gm2m反向关系.关系 [英] Reverse relations with django-gm2m using "through" relation
问题描述
我不知道如何使用django-gm2m反向遵循多对多关系.这是models.py的示例:
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和Y都具有事物",其中包含多个任意对象.是我遇到问题的Y,而X仅用于比较.
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()
等有了X班,我就可以做到
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)
,然后用x1.things.all()
等返回添加的内容.要反向执行,请像a1.x_set.count()
一样使用x_set
.
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()
.
到目前为止,一切都很好.对于使用通过"的"Y",我会这样做
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()
添加两个事物",然后我可以再次使用y1.things.all()
来获取列表.但是,如何从a1
进行反向查找以查看其使用位置?
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?
推荐答案
如 django-gm2m只能在将实例添加到*_set
后(与对X
对象所做的一样)创建相关的反向关系,因为它不能知道在哪个模型上需要反向关系.
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)
这在某种程度上类似于Django的行为,在该行为中,您还必须为GenericForeignKey
This somehow resembles Django's behaviour where you would also have to create the reverse relation for GenericForeignKey
manually.
这篇关于使用“直通"与django-gm2m反向关系.关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!