Issue with comparison of Count outcome in queryset

167 views
Skip to first unread message

Magnus Ljungkrantz

unread,
Jul 4, 2018, 6:37:27 PM7/4/18
to Django users

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?

 

Jason

unread,
Jul 5, 2018, 7:24:31 AM7/5/18
to Django users
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.  

Magnus Ljungkrantz

unread,
Jul 5, 2018, 5:23:06 PM7/5/18
to Django users
Actually, I tried to do it that way but I never got it working. Not sure what is different now but this is what I have working for me now:  

qs = qs.values('make').annotate(model_count=Count('model', distinct=True)).annotate(
   
more_than_one_model=Case(
       
When(model_count__gt=1, then=Value('yes')),
       
default=Value('no'),
        output_field
=CharField()
   
)
)  

Thanks for leading me back on the right track.
Reply all
Reply to author
Forward
0 new messages