通用关系模型声明

时间:2018-02-14 03:45:10

标签: django django-models generic-relations

只是一个快速的菜鸟问题。每次在模型中使用GenericRelation时,是否需要content_type,object_id和content_object?我得到了泛型关系背后的概念,但我对如何实现它感到困惑。

以下是设置。

地址 - 通用内容类型;用于不同的模型。

公司 - 使用地址通用内容类型的简单模型。

- 使用地址通用内容类型的简单模型。

在所有模型中拥有这三个属性是否必不可少?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您只需要Address型号内的此字段:

class Address(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

在模型CompanyPerson中,您只需指定与GenericRelation的反向通用关系:

from django.contrib.contenttypes.fields import GenericRelation
class Company(models.Model):
    addresses = GenericRelation(Address)

class Person(models.Model):
    addresses = GenericRelation(Address)

有了这个,你可以得到与这样的人相关的地址:

 person.addresses.all()