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

Time:09-27

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=...)

CodePudding user response:

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

CodePudding user response:

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