1

Can anyone help me with this

 qs = Vine.objects.annotate(votos_count=Count('votomoderacion')).\
            annotate(votos_ok=Count('votomoderacion')).filter(votomoderacion__voto="1").\
            annotate(votos_no_ok=Count('votomoderacion')).filter(votomoderacion__voto="0")

The problem is that the filters affects to all the annotations, and i want to filter every single annotation separately.

I hope i've been clair enough with my question.

Thank you!

Miki Torandell
  • 163
  • 1
  • 11

1 Answers1

0

You have to understand that what you are doing is chaining filters.

First you had a queryset with annotated votes count likeannotate(votos_ok=Count('votomoderacion')).filter(votomoderacion__voto="1").

Then you annotated votes_ok with it and filterered it like annotate(votos_ok=Count('votomoderacion')).filter(votomoderacion__voto="1"), which gave you another filtered queryset.

But after that, you added another filter annotate(votos_no_ok=Count('votomoderacion')).filter(votomoderacion__voto="0"), which filtered the queryset which you got from previous filter. so, in this case, you didn't get your desired result.

So better if you separate them. Like:

total_votes= Vine.objects.annotate(votos_count=Count('votomoderacion'))
yes_votes= Vine.objects.annotate(votos_ok=Count('votomoderacion')).filter(votomoderacion__voto="1")
no_votes= Vine.objects.annotate(votos_no_ok=Count('votomoderacion')).filter(votomoderacion__voto="0")

To join those queryset:

from itertools import chain
allvotes = list(chain(total_votes, yes_votes, no_votes))
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Thanks @ruddra, but i need all of these querysets in 1 queryset.There's some way to join them? – Miki Torandell Jun 30 '14 at 09:44
  • Hi @ruddra, thanks for your help, but i'm getting this error when trying to chain: 'list' object has no attribute 'filter'. Any suggestion? – Miki Torandell Jun 30 '14 at 10:25
  • Well you chain queries using `list()`, then you get a list, which doesn't have filter function. – ruddra Jun 30 '14 at 10:57
  • The problem is, since I'm using this in the modeladmin queryset,I need this as queryset, and not as list, there's any way to achieve this? Thank you so much! – Miki Torandell Jun 30 '14 at 10:59
  • I am not sure, as the list made by chaining shouldn't have proper order. You can check here: http://blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html – ruddra Jun 30 '14 at 11:08
  • also, you can check here about chaining: http://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view – ruddra Jun 30 '14 at 11:09