Rob
Rob

Reputation: 3459

Annotate a Django query for all users in admin panel

I have a query like this:

user.ihaveinvited.all().filter(current_status='passive').values('id').distinct()

to get all the distinct users with a certain status. I want to apply this to something like:

def get_queryset(self, request):
    qs = super(UserAdmin, self).get_queryset(request)
    qs = qs.annotate(uniq_passive_invites=ALLUSERS.ihaveinvited.all().filter(current_status='passive').values('id').distinct()

so the question is running this query for all users as a queryset?

Upvotes: 1

Views: 416

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13058

I had a look at another question you posted and they seemed closely related. Adding a count with a filter requires a bit more work, but it can be achieved.

def get_queryset(self, request):
    qs = super(UserAdmin, self).get_queryset(request)
    qs = qs.annotate(count=Sum(
        Case(
            When(ihaveinvited__invitee__current_status='passive', then=1),
            default=0,
            output_field=models.IntegerField()
        )
    ))
    return qs

Upvotes: 1

Related Questions