[Django]-Django model based on an SQL table-valued function using MyModel.objects.raw()

2👍

Guess you’ve figured this out by now (see docs):

MyModel.objects.raw('select * from dbo.f_mytablefunction(%s)', [1])

If you’d like to map your table valued function to a model, this gist has a quite thorough approach, though no license is mentioned.

Once you’ve pointed your model ‘objects’ to the new TableFunctionManager and added the ‘function_args’ OrderedDict (see tests in gist), you can query it as follows:

MyModel.objects.all().table_function(param1=1)

For anyone wondering about use cases for table valued functions, try searching for ‘your_db_vendor tvf’.

Leave a comment