Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-aggregationdjango-annotate

Perform trigonometric operations or any mathematical expression in Django annotate


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.


Solution

  • 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
            )
        )
    )