0

I have a table which is having latitude and longitude fields.

`

location.objects.annotate( distance =math.fabs(math.pow((math.sin( 
                    F('latitude') - float(90.378770)) /2 )),2) + 
                    math.cos(90.378770) * math.cos( F('latitude')) * 
                    pow((math.sin(  (F('longitude') - float(-59.826830)) /2)),2) )
                   ).values_list('distance', flat=True)

`

How to do perform this equivalent mathematical operation on data and store the values in a list while doing database query.

Ab1gor
  • 398
  • 3
  • 19

1 Answers1

2

According to documentation

Django supports negation, addition, subtraction, multiplication, division, modulo arithmetic, and the power operator on query expressions, using Python constants, variables, and even other expressions.

To perform trigonometric operations like sin and cos as query expressions you'll need Func() expressions to involve database functions inside a queryset

from django.db.models import F, Func


class Sin(Func):
    function = 'SIN'

class Cos(Func):
    function = 'COS'


latitude = 90.378770
longitude = -59.826830


Location.objects.annotate(
    distance=(
        Sin((F('latitude') - latitude)/2)**2 +
        (
            Cos(F('latitude'))*Cos(latitude)*
            Sin((F('longitude') - longitude)/2)**2
        )
    )
)
Lucas Weyne
  • 1,107
  • 7
  • 17
  • What are the other available functions in func() ? This worked well and also made the code look a lot cleaner – Ab1gor Jan 13 '19 at 14:10
  • All available functions in django are distributed into the `django.db.models.function` package (look at [github](https://github.com/django/django/tree/2.1.5/django/db/models/functions), switch to the tag version there are you using). There are a `django.db.models.functions.math` package in **development** (see [documentation](https://docs.djangoproject.com/en/dev/_modules/django/db/models/functions/math/)) with many math functions like `Sqrt`, `Radians`, `Atan`, `Sin`, etc. – Lucas Weyne Jan 13 '19 at 19:42