6👍
✅
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
1👍
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
👤ayaz
Source:stackexchange.com