简体   繁体   中英

How to annotate more than one value in Django

I want to expand existing queryset.

I tried the following:

def queryset(self, request):
    qs = super(MyAdmin, self).queryset(request)
    qs = qs.annotate(models.Count('article'))
    return qs

It works perfectly for one annotation. But how can I add more?

def queryset(self, request):
    qs = super(MyAdmin, self).queryset(request)
    qs = qs.annotate(models.Count('article'))
    qs = qs.annotate(models.Count('comment'))
    return qs

With above solution results go crazy. When it should show:

  • 2 articles
  • 2 comments

it shows:

  • 4 articles
  • 4 comments

you should use this

Count('article', distinct=True)

def queryset(self, request):
    qs = super(MyAdmin, self).queryset(request)
    qs = qs.annotate(models.Count('article', distinct=True))
    qs = qs.annotate(models.Count('comments', distinct=True))
    return qs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM