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?