Can anybody help with this problem on django queryset distinct/order with annotated fields?
THIS WORKS
It returns nicely and called my Serializer after, no problem at all.
def get_queryset(self) -> list:
distinct_by = ('distance_to_first_point', 'id')
pnt = create_point(float(lat), float(lng))
queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point")
return queryset.order_by(*distinct_by).distinct(*distinct_by)
THIS DOENSN’T WORK
If I try to access any field on the queryset it gives me this error:
Cannot resolve keyword ‘distance_to_first_point’ into field
I’m assuming the error is due to the annotated field, but Why?
Before the distinct and order I can access queryset[0].distance_to_first_point for example and it works also..
def get_queryset(self) -> list:
distinct_by = ('distance_to_first_point', 'id')
pnt = create_point(float(lat), float(lng))
queryset = queryset.annotate(distance_to_first_point=Distance("first_point",pnt)).order_by("distance_to_first_point")
queryset = queryset.order_by(*distinct_by).distinct(*distinct_by)
queryset_ids = queryset.values_list('id', flat=True)
return queryset