Django Count() in multiple annotations

后端 未结 2 1122
我寻月下人不归
我寻月下人不归 2021-01-30 20:34

Say I have a simple forum model:

class User(models.Model):
    username = models.CharField(max_length=25)
    ...

class Topic(models.Model):
    user = models.F         


        
2条回答
  •  终归单人心
    2021-01-30 21:11

    I think Count('topics', distinct=True) should do the right thing. That will use COUNT(DISTINCT topic.id) instead of COUNT(topic.id) to avoid duplicates.

    User.objects.filter(
        username_startswith="ab").annotate(
        posts=Count('post', distinct=True)).annotate(
        topics=Count('topic', distinct=True)).values_list(
        "username","posts", "topics")
    

提交回复
热议问题