N
N
NyxDeveloper2021-11-30 15:21:39
Django
NyxDeveloper, 2021-11-30 15:21:39

How to annotate a Django calculated field?

You need to sort the data array by distance from the current location. Objects have a reference to an address that has a longitude and latitude. I'm trying to create additional fields by calculating with the formula:

√ ((x A - x B) 2 + (y A - y B) 2)

I get the following code:
queryset.annotate(distance=((longitude - F("address__longitude")) * 2) + ((latitude - F("address__latitude")) * 2)).order_by("distance")

Where longitude is the current longitude and latitude is the current latitude. But an error is thrown
Expression contains mixed types: FloatField, DecimalField. You must set output_field.
but I don't know where to add this attribute.
How to create such a field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-11-30
@NyxDeveloper

from django.db.models import ExpressionWrapper, F


queryset.annotate(
    distance=ExpressionWrapper(
        expression=((1 - F("address__longitude")) * 2) + ((1 - F("address__latitude")) * 2),
        output_field=models.FloatField,
    ),
) \
.order_by("distance")

PS Do not do such garbage, PostGIS is for this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question