I’ve written a pair of SQL functions that work well when I run them directly from SQL scripts and now I’m trying to run them from Manager.raw(). The first runs fine with both a standalone SQL script and with Manager.raw(). In this case I have an instance method where I pass self.id to my SQL function which then returns a temporary table that Manager.raw() consumes:
def get_store_products_sql(self) -> list['Product']:
return Product.objects.raw(
'''SELECT prod_id AS id,
prod_name,
prod_price
FROM get_store_products(%s)''',
(self.id,)
)
In the second case have a “regular” method where I pass a string argument to a SQL function which expects a VARCHAR. The SQL function should then return a temporary table for Manager.raw() to consume:
def get_products_by_color_sql(color) -> list['Product']:
return Product.objects.raw(
'''SELECT prod_id AS id,
prod_name,
prod_price
FROM get_products_by_color(%s)''',
(color,)
)
This SELECT statement works when I run it in a SQL script but it fails pretty silently when I run it with Manager.raw() as shown above. It returns a RawQuerySelect iterator object with a correct params value. But when I try to iterate it, it has a length of 0. I’ve tried stepping through this with pdb, but I can’t find anything. I know that I need to return an id field from the SELECT statement and for that I’m taking the same approach as in the first example.
I’ve put RAISE statements in my get_products_by_color() function and they aren’t getting called, so I doubt the problem is with my SQL function.
I know this is a bare example, but since this a demo for now I can also put up a full repo on GitHub.