How do I use a DB procedure from the django ORM?

For example, in MySQL, I would write:

SELECT id, my_calc(id, '2022-09-26') as calculated
FROM items;

How do I tell the ORM to use this DB procedure and pass the parameters? Would I have to define a Func?

Items.objects.annotate(calculated=...)

obviously through Func expression. More here: https://docs.djangoproject.com/en/4.1/ref/models/expressions/#func-expressions

in your case (postgres):

self.annotate(calculated=Func(F('id'), Value('2022-09-26), function='public.MY_CALC', output_field=CharField()))

Define the new function:

from django.db.models import Func

class MyCalc(Func):
    function = 'my_calc'
    arity = 2 # requires 2 arguments

Use it:

from django.db.models import Value

Items.objects.annotate(calculated=MyCalc(F('id'), Value('2022-09-26'))
Back to Top