【问题标题】:How do I retrieve objects linked through Django generic relations and determine their types?如何检索通过 Django 泛型关系链接的对象并确定它们的类型?
【发布时间】:2025-12-09 02:00:01
【问题描述】:

这是我的models.py

class Player(models.Model):
    name = models.CharField(max_length=100)
    #...fields...
    comment = models.generic.GenericRelation(Comment)   

class Game(models.Model):
    name = models.CharField(max_length=100)
    #...other fields...
    comment = models.generic.GenericRelation(Comment)  

class Comment(models.Model):
    text = models.TextField()
    content_type = ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

要从 Player 或 Game 转到评论,我可以这样做吗?

text = PlayerInstance.comment.text

另外,有评论我不知道如何找出我最终的结果(哪个型号)

CommentInstance = get_object_or_404(Comment, pk=coment_id)

以及如何测试 CommentInstance 指向哪个 content_type(游戏或播放器),然后如何连接?

【问题讨论】:

    标签: python database django django-models foreign-key-relationship


    【解决方案1】:

    Django 中泛型关系的文档可以在这里找到https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations

    您应该能够像这样访问 content_object:

    linked_object = CommentInstance.content_object
    

    如果你想知道这是什么类型的对象,你可以使用typeisinstanceissubclass 来询问它,就像在 python 中的任何对象一样。试试这个

    linked_object_type = type(linked_object)
    

    因此,如果您想根据它是 Player 还是 Game 来做不同的事情,您可以做类似的事情

    if isinstance(linked_object, Player):
        # Do player things
    elif isinstance(linked_object, Game):
        # Do game things
    else:
        # Remember it might be something else entirely!
    

    我假设您在这里希望CommentInstance 的属性称为playergame。这些不存在 - 你甚至不知道你在上面的 models.py 中有什么,它肯定是这两种类型的对象之一。

    PS 你可能想在你的 models.py 文件中重新排序,把 Comment 放在其他两个之前。

    【讨论】:

      最近更新 更多