sablam
sablam

Reputation: 69

Django - Query with extra method that use python Function

I would like to make a query in Django that use a function that take parameters from db e from python program. The function is shown below:

> def myFunc(a, b):
>     val = mathematical expression with a and b
>     return val

I would like that:

class myTable(models.Model):
   num = models.IntegerField(default=0)

I would like to do a query similar to this in views.py:

b = 4     #it must be variable
c = 10    #it must be variable
myTable.objects.all().extra(select = {'new_param' : myFunc(num , b)}, where = ['new_param > %d'], params = [c]) 

How can I do that?

Upvotes: 1

Views: 884

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

You'll need to change your function to be an annotation using database functions because you can't pass arbitrary python code in a query to run on the database. Something like the following should be close to the expression inn your comment although it was a bit hard to read and is a bit complex

from django.db.models import F, Value
from django.db.models.functions import Cos, Sin, Abs, Power, Sqrt, ASin
b = 4
c = 10
myTable.objects.annotate(
    new_param=ASin(Sqrt(Power(Cos(F('num')) * Sin(Abs(Value(b) - F('num')))), Value(2)) + Value(1))
).filter(new_param__gt=c)

Upvotes: 1

Related Questions