vijay shanker
vijay shanker

Reputation: 2663

Annotation with generic ForeignKey

i have a model Article which goes on like this.

class Article(models.Model):
    title = models.CharField(max_length=255)
    title_slug = models.SlugField(max_length=255, null=True, blank=True, unique=True)
    body = RichTextField()

I store comments on article in a table with a GenericForeignKey as I wanted to use the commenting feature on models of different types, like this:

class Comment(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    comment = models.TextField(null=True, blank=True)

How can I find the most commented Article?

Upvotes: 0

Views: 1097

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

Have a look at the 'reversing generic keys' section of the documentation

You add a GenericRelation to your Article model to make reversing it easier:

from django.contrib.contenttypes.generic import GenericRelation
class Article(...):
    ...
    comments = GenericRelation(Comment)

then you can simply use the annotate model method to find the article with the most comments and order them them:

from django.db.models import Count
...
articles = Article.objects.all().annotate(comment_count=Count("comments")).order_by("comment_count)
if articles: 
    most_commented = articles[0]

Upvotes: 3

Related Questions