开发者

How do I retrieve objects linked through Django generic relations and determine their types?

开发者 https://www.devze.com 2023-03-26 23:06 出处:网络
Here is my models.py: class Player(models.Model): name = models.Char开发者_运维问答Field(max_length=100)

Here is my models.py:

class Player(models.Model):
    name = models.Char开发者_运维问答Field(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?


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:

linked_object = CommentInstance.content_object

If you want to find out the what sort of object this is, you could ask it by using type, isinstance or issubclass, like you can with any object in python. Try this

linked_object_type = type(linked_object)

So if you wanted to do different things based on it being a Player or a Game, you could do something like

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

I assume you were hoping here for attributes of CommentInstance called something like player or game. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消