如何获取通过Django通用关系链接的对象并确定它们的类型?

3 投票
1 回答
2192 浏览
提问于 2025-04-16 23:20

这是我的 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)到评论(comment),我可以直接这样做吗?

text = PlayerInstance.comment.text

另外,拿到一个评论后,我不知道怎么找到它对应的是哪个模型(model)。

CommentInstance = get_object_or_404(Comment, pk=coment_id)

还有,我该如何测试评论实例(CommentInstance)指向的是哪种内容类型(Game 或 Player),然后又该如何连接到它呢?

1 个回答

3

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

你可以这样访问内容对象:

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中看到的内容,根本无法确定它一定是这两种类型的对象之一。

另外,你可能想在models.py文件中调整一下顺序,把Comment放在其他两个之前。

撰写回答