姜戈。如何获取GenericForeignKey对应的对象

Ale*_*lla 4 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)
Run Code Online (Sandbox Code Playgroud)

如何获取所GenericForeignKey指向的对象?

Dan*_*man 6

您只需像访问其他字段一样访问它即可。

my_discount_obj.discount_target
Run Code Online (Sandbox Code Playgroud)