【问题标题】:generic relation model declaration泛型关系模型声明
【发布时间】:2018-07-24 13:28:04
【问题描述】:

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

下面是设置。

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

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

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

在所有模型中都必须具有这 3 个属性吗?提前致谢!

【问题讨论】:

    标签: django django-models generic-relations


    【解决方案1】:

    您只需要在 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 2018-12-14
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多