On Mon, Aug 18, 2014 at 7:17 PM, <9devmail@gmail.com> wrote:
>
>> As an aside, this can probably be written as:
>>
>> current_user_vote = item.vote_set.filter(user=request.user)
>>
>> >
>> > I tried to use annotate() two times, however it filtered out everything
>> > except items current user voted on.
>>
>> Just use it once.
>
>
> Thank you for answer, however I still can't see how can I do it.
>
> Using annotate only once won't let me use filter() to exclude users
> different than the current one.
>
> Item.objects.annotate(
> score=Sum('votes__value'),
> current_user_vote=Sum('votes__value')
> )
>
It's unclear to me what you are trying to do. Are you trying to
annotate the item with two values, or are you trying to restrict the
values that are used to calculate the annotation, so that only the
current users votes are counted?
If you are trying to restrict the votes counted to just that user,
then this might suit:
Item.objects.filter(votes__user=request.user).annotate(score=Sum('votes__value'))
If you're trying to do both in one query, then I'm not sure that is
possible as you would need to join to the votes table multiple times
with different join conditions. It's technically possible, so you
could easily write it in a Foo.objects.raw() call, but I'm not sure
the API exposes a way to do it neatly.
However, given a specific user and a set of items (or even all items),
it would be trivial to get all their current quotes in one additional
query:
Votes.objects.filter(
user=request.user).values_list(
'item_id', 'value')
Don't waste time on premature optimisation!
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JM3ZW%2BRUytdd8Dat2DTAvLHzvwow%2Ba4MZ1oYb7_9vsOw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment