Django queryset with annotate, order_by and distinct raises error when values is called
Can somebody explain to me why the following call works fine
Order.objects.filter(part_description__icontains=search_query)
.annotate(part_description_lower=Lower('part_description'))
.order_by("part_description_lower", '-pk')
.distinct("part_description_lower")
But the following raises the error Cannot resolve keyword 'part_description_lower' into field
Order.objects.filter(part_description__icontains=search_query)
.annotate(part_description_lower=Lower('part_description'))
.order_by("part_description_lower", '-pk')
.distinct("part_description_lower")
.values('pk')
Thank you in advance.
when you add .values('pk')
it alters the structure of the queryset in such a way that
.values()
generates a queryset of dictionaries containing only the specified fields (pk
in this case).- the annotated fields (like
part_description_lower
) are no longer part of the queryset output. - when distinct("
part_description_lower
") is called, django cannot resolvepart_description_lower
because it is no longer available in the queryset context.