1

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:

  • a comes from myTable (represent the field 'num')
  • b comes from python Code
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?

3
  • You can't run arbitrary python code as part of a query, if it's some mathematical expression it is probably possible using database functions. Can you share the actual contents of myFunc? Commented Aug 9, 2022 at 12:34
  • An example of myFunc() can be def myFunc(a,b): val = numpy.arcsin(math.sqrt( ((math.cos(a) * math.sin(abs(b - a))) ** 2) + 1) retun val Commented Aug 9, 2022 at 12:43
  • The function works correctly, and b is passed correctly as well. The problem is to pass the 'num' value of the database to the function. Do you know another way? Commented Aug 9, 2022 at 12:49

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Using F(' ') the query works also using myFunc(), the function that I wrote. F(' ') was what was missing. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.