beren5000
beren5000

Reputation: 100

How to annotate a postgis distance in a queryset in an specific unit?

i have a queryset in which i annotate the distance between a point and the location of the object like this:

distance_subquery = Headquarter.objects.filter(
    organization_id=OuterRef('pk'),
    location__distance_lte=(search_location_center, D(m=distance))
).annotate(
    distance=Distance('location', search_location_center)
).order_by(
    'distance'
).values(
    'distance'
)[:1]

how can i get the distance in an specific metric unit?, this parameter could be a variable in some way?

as the documentation said, the distance function returns a distance object, and you could use distance."metric_unit" for get the distance in an specific unit, but i get and error

there is a way i can have control over the annotated distance?

Upvotes: 0

Views: 338

Answers (1)

joe
joe

Reputation: 9503

I use serializer to deal with annotated field like this

from rest_framework import serializers

from garages.models import Garage


class GarageSerializer(serializers.ModelSerializer):
    distance = serializers.DecimalField(
        source='distance.km', max_digits=10, decimal_places=2, read_only=True)

    class Meta:
        model = Garage
        fields = [
            'name_en',
            'name_th',
            'point',
            'distance',
        ]
        read_only_fields = ('point',)

Upvotes: 1

Related Questions