如何纠正设置通用关系?

时间:2017-12-13 23:02:45

标签: python django

class A(models.Model):
    relation = GenericRelation('B')
    another_relation = GenericRelation('B')

class B(models.Model):
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content = GenericForeignKey('content_type', 'object_id')

a = A()
b = B()

如何设置连接以便我得到b作为a.another_relation.all()的结果?

1 个答案:

答案 0 :(得分:0)

Django documentation GenericRelation获取该类作为第一个参数。

class B(models.Model):
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content = GenericForeignKey('content_type', 'object_id')

class A(models.Model):
    relation = GenericRelation(B)
    another_relation = GenericRelation(B)

然后您应该可以使用a.another_relation.all()