Hello Daniel,

It's hard to tell was causes the exception without digging a bit more but
based on your mention of multiple sums I assume you are trying to work
around the cross join of multiple table annotations?

I understand you simplified your query but from what I can see right now
it can be expressed as

commens_count = Comment.objects.annotate(
    votes_count=Count('votes', filter=votes_filter),
).filter(
    votes_count__gte=4
).count()

That should result in

SELECT COUNT(*) FROM (
    SELECT 1
    FROM comment
    LEFT OUTER JOIN vote ON (vote.comment_id = comment.id)
    GROUP BY comment.id
    HAVING COUNT(*) FILTER (WHERE ...) > 4
)

There's tickets tracking adding subquery support to aggregate functions but
using subqueries doesn't seem to be necessary here?

Cheers,
Simon

Le mercredi 5 décembre 2018 19:16:30 UTC-5, Daniel Gilge a écrit :
>
> Hi,
>
> I think I've found a bug. But I'm not sure and I never opened a ticket for 
> Django before. So, I first wanted to ask here.
>
> I'm using Django 2.0 and this doesn't work:
>
> subquery = Subquery(
>     Vote.objects
>     .filter(comment=OuterRef('pk'))
>     .values('value')[:1]
> )
>
> Comment.objects.annotate(vote=subquery).aggregate(
>     count=Count('vote', filter=Q(vote__gte=4)),
> )
>
> It results in a quite useless AssertionError:
>
> django/db/models/expressions.py
>
>
>     168     169     def set_source_expressions(self, exprs):--> 170         
> assert len(exprs) == 0    171     172     def _parse_expressions(self, 
> *expressions):
> AssertionError:
>
>
>
> Vars:
> exprs 
>
> [Ref(__col8, Col(U0, myapp.Vote.comment))]
>
> self 
>
> <django.db.models.expressions.Subquery object at 0x1080077b8>
>
>
>
> It probably doesn't make sense because I simplified it. Why I'm using 
> subqueries is that I have several sums involved in the query:
>
> subquery = Subquery(
>     Vote.objects
>     .filter(comment=OuterRef('pk'))
>     .values('comment_id')
>     .annotate(sum=Sum('value', filter=Q(**filter_fields)))
>     .values('sum')[:1]
> )
>
> However, what I had to remove is a filter statement and then it works:
>
> Comment.objects.annotate(vote=subquery).aggregate(
>     count=Count('vote'),
> )
>
> Any advice appreciated!
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/44dcbf0e-e766-4ba9-a9e6-05ebf1a1709f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to