Django的。如何获取与GenericForeignKey对应的对象

时间:2018-01-24 09:07:41

标签: django django-models

简单的问题。我有这个模型:

class Discount(models.Model):
    discount_target = GenericForeignKey('content_type', 'object_id')
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)

如何获取GenericForeignKey指向的对象?

2 个答案:

答案 0 :(得分:2)

您只需像访问任何其他字段一样访问它。

my_discount_obj.discount_target

答案 1 :(得分:1)

您可以创建一个特殊函数来获取相关对象。

class Discount(models.Model):
    ....


    def get_related_object(self):
        """
        return the related object of content_type.
        eg: <Question: Holisticly grow synergistic best practices>
        """
        # This should return an error: MultipleObjectsReturned
        # return self.content_type.get_object_for_this_type()
        # So, i handle it with this one:
        model_class = self.content_type.model_class()
        return model_class.objects.get(id=self.object_id)


    @property
    def _model_name(self):
        """
        return lowercase of model name.
        eg: `discount`, `transaction`
        """
        return self.get_related_object()._meta.model_name