try making two separate annotates: one for count and one for the case-when

qs.values('make')
    .annotate(count = Count('model', distinct = True))
    .annotate(Case(When(count__gt = 1, then='yes', output_field=CharField())

Basically, you need to transform the count annotation into something django 
can use its lookup syntax with.  
On Wednesday, July 4, 2018 at 6:37:27 PM UTC-4, Magnus Ljungkrantz wrote:
>
>
> To give you simplest possible example of my problem, let us say we have a 
> table holding data about physical cars. It has many fields but "make" and 
> "model" are two of them. 
>
> The following SQL will group on make and let me know with "yes "or "no" 
> whether there is more than one model within each group of cars of a 
> specific make. 
>
> SELECT 
>  make,
>  CASE WHEN COUNT(DISTINCT model) > 1 THEN 'yes' ELSE 'no' END AS 
> more_than_one_model
> FROM myapp_car
> GROUP BY make
>
> I know how to group on make and count unique models s  
>
> qs = Car.objects.all().values('make').annotate(model_count=Count('model', 
> distinct=True))
>
> but I cannot figure out how to produce "yes" or "no" result depending on 
> the outcome of a Count(). The following 
>
> qs = qs.values('make').annotate(
>     more_than_one_model=Case(
>         When(Count('model', distinct=True) > 1, then='yes'),
>         default='no'
>     ),
>     output_field=models.CharField()
> )
>
>
> gives me an exception saying "'>' not supported between instances of 'Count' 
> and 'int'".
>
>
> Any ideas how to accomplish this?
>
>
>  

-- 
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/c2fbc7a6-54c5-4163-aa1b-c84b13fe5239%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to