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 visit from Player or Game to some comment can one simply do this?
text = PlayerInstance.comment.text
Also, getting a comment I'm not sure how you can discover where I finish up (which model)
CommentInstance = get_object_or_404(Comment, pk=coment_id)
And just how to check which content_type the CommentInstance indicates (Game or Player) after which how you can connect with it?
The documentation for generic relations in Django are available here https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
You need to have the ability to access this content_object like so:
linked_object = CommentInstance.content_object
If you wish to discover the what kind of object this really is, you can request it by utilizing
issubclass, as if you can with any object in python. Do this
linked_object_type = type(linked_object)
If you desired to do various things according to it as being a Player or a game title, you could do this something similar to
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 suppose you had been wishing for characteristics of
CommentInstance known as something similar to
game. These don't exist - you do not know from that which you have above inside your models.py that it'll certainly be one of these simple two kinds of object.
PS You might like to reorder things inside your models.py file to place Comment prior to the other two.