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

3👍

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.

Leave a comment