如何检索通过 Django 通用关系链接的对象并确定它们的类型?
这是我的 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()
要从玩家或游戏转到评论,我可以这样做吗?
text = PlayerInstance.comment.text
另外,有评论我不知道如何找出我最终的位置(哪个模型)
CommentInstance = get_object_or_404(Comment, pk=coment_id)
以及如何测试 CommentInstance 指向哪个 content_type(游戏或玩家),然后如何连接到它?
Here is my 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()
To go from Player or Game to a comment can I just do this?
text = PlayerInstance.comment.text
Also, having a comment I don't know how to find out where I end up (which model)
CommentInstance = get_object_or_404(Comment, pk=coment_id)
And how to test which content_type the CommentInstance points to (Game or Player) and then how to connect to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 中通用关系的文档可以在这里找到 https:// /docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
您应该能够像这样访问 content_object:
如果您想找出这是什么类型的对象,您可以使用
type
、isinstance
或issubclass
来询问它,就像使用 python 中的任何对象一样。试试这个所以如果你想根据它是一个玩家还是一个游戏来做不同的事情,你可以做类似的事情,
我假设你希望这里有
CommentInstance
的属性,称为player< /code> 或
游戏
。这些不存在 - 你甚至不知道你的 models.py 中的内容肯定是这两种类型的对象之一。PS 您可能需要重新排序 models.py 文件中的内容,将 Comment 放在其他两个文件之前。
The documentation for generic relations in Django can be found here https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
You should be able to access the content_object like so:
If you want to find out the what sort of object this is, you could ask it by using
type
,isinstance
orissubclass
, like you can with any object in python. Try thisSo if you wanted to do different things based on it being a Player or a Game, you could do something like
I assume you were hoping here for attributes of
CommentInstance
called something likeplayer
orgame
. These don't exist - you don't even know from what you have above in your models.py that it will definitely be one of these two types of object.PS You might want to reorder things in your models.py file to put Comment before the other two.