When using django.contrib.comments is there anyway to add the reverse relationship to a model that has comments?
For example:
post = Post.objects.all()[0]
comments = post.comments.all()
When using django.contrib.comments is there anyway to add the reverse relationship to a model that has comments?
For example:
post = Post.objects.all()[0]
comments = post.comments.all()
Yes, you should be able to do:
from django.contrib.contenttypes import generic
class Post(models.Model):
...
comments = generic.GenericRelation(Comments)
per the Django docs on reverse generic relations
I came up with another way to do this (why? Because I wasn't aware of any other way to do that time). It relies on having an abstract model class from which all models in the system are derived. The abstract model itself has a method, comments
, defined which when called returns a QuerySet
of all the comment objects associated with the corresponding concrete object. I implemented it thus:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
class AbstractModel(models.Model):
def comments(self):
"""Return all comment objects for the instance."""
ct = ContentType.objects.get(model=self.__class__.__name__)
return Comment.objects.filter(content_type=ct,
object_pk=self.id)
class Meta:
abstract = True