DRF注释通过表的多对多计数比使用_set.all()时出现的次数更多.count()

时间:2018-01-12 16:04:10

标签: python django django-rest-framework

我有这些模特:

class Topic(BaseModel):

    name = models.CharField(max_length=60)
    public_name = models.CharField(max_length=60, blank=True, null=True)

class Content(BaseModel):

    title = models.CharField(max_length=120)
    series = models.CharField(max_length=120, blank=True, null=True)
    season = models.CharField(max_length=45, blank=True, null=True)
    episode = models.CharField(max_length=45, blank=True, null=True)
    tags = models.ManyToManyField(tags_models.Tag, through='ContentHasTags')
    topics = models.ManyToManyField(topics_models.Topic, through='ContentHasTopics')

class ContentHasTopics(BaseModel):

    content = models.ForeignKey(Content)
    topic = models.ForeignKey(topics_models.Topic)

    order = models.IntegerField(default=99)

    class Meta:
        unique_together = ('content', 'topic',)
        ordering = ('order',)

我遇到的问题是,如果我使用下一个功能:

@property
def get_contents_count(self):
    return self.contenthastopics_set.all().count()

在很多情况下,我有7个结果(并且是真的),但是当我为Django Rest Framework(在视图集中)使用这样的注释查询时,它给了我28个结果,其他一些主题有5个内容使用_set.all()。count(),但是注释会给我10个结果,依此类推。

queryset = models.Topic.objects.all().annotate(
    themes_count=Count('themehastopics')
).annotate(
    contents_count=Count('contenthastopics')
).annotate(
    tags_count=Count('topichastags')
)

如何正确添加计数来正确注释查询?

1 个答案:

答案 0 :(得分:0)

这终于是我如何解决这个问题的:

queryset = models.Topic.objects.all().annotate(
    themes_count=Count('themehastopics', distinct=True),
    contents_count=Count('contenthastopics', distinct=True),
    tags_count=Count('topichastags', distinct=True)
)