Home > OS >  How to make calculation inside django annotate?
How to make calculation inside django annotate?

Time:02-21

This one when I run generates error:

qs = UserLocation.objects.annotate(distance=0.5 - cos((F('lat')-lat1)*p)/2   cos(lat1*p) * cos(F('lat')*p) * (1-cos((F('long')-lon1)*p))/2).all()

The error it generates is this one:

must be real number, not CombinedExpression

How can I make that calculation as an annotation

CodePudding user response:

Try adding ExpressionWrapper as described here: https://docs.djangoproject.com/en/3.2/ref/models/expressions/#using-f-with-annotations

qs = UserLocation.objects.annotate(distance=ExpressionWrapper(0.5 - cos((F('lat')-lat1)*p)/2   cos(lat1*p) * cos(F('lat')*p) * (1-cos((F('long')-lon1)*p))/2).all(), output_field=FloatField())

I might missed some ) because your calculation is complicated and I assumed that result is a float

  • Related