使用通用ForeignKey的注释

时间:2014-02-03 16:32:41

标签: django django-models django-queryset

我有一个模型Article,就像这样。

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()

我将评论文章存储在带有GenericForeignKey的表格中,因为我想在不同类型的模型上使用评论功能,如下所示:

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)

如何找到评论最多的Article

1 个答案:

答案 0 :(得分:1)

查看文档的'reversing generic keys'部分

您在GenericRelation模型中添加了Article,以便更轻松地进行逆转:

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

然后你可以简单地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]