我试图在模型A中设置我的通用关系:
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')
然而,当我尝试做的时候:
relation = B.objects.get(pk=1)
model = A(relation=relation).save()
我收到此错误:
TypeError:' B'对象不可迭代
答案 0 :(得分:1)
GenericRelation是关系的 reverse 方面。与普通的ForeignKey一样,可能有许多项链接到B的任何特定实例。
你需要这样做:
relation = B.objects.get(pk=1)
relation.content = A().save()
relation.save()