Ross Rogers
Ross Rogers

Reputation: 24228

In django, can I set a variable in a preamble before retrieving a queryset?

I need to variably group data points according to a user-defined stride and I would like to minimize the amount of raw SQL in my code that is interfacing with django. The question "Can I create view with parameter in MySQL?", seems like a great way to create a parameterized view, but it requires that I somehow set a variable before the main query is executed.

Thus, how would I set a parameter value in the mysql connection before any query is executed on the queryset? If I have the model Foo and I do the very basic:

Foo.objects.all()

How could I inject the following as a preamble to any code that is being emitted by the django ORM to SQL compiler ?

set @my_param := 5;

Upvotes: 2

Views: 271

Answers (1)

Ross Rogers
Ross Rogers

Reputation: 24228

I think I have a solution which works for my current MySQL backend. I believe it may depend on unspecified order of evaluation and could break in the future version changes:

Foo.objects.extra(where=('5 = (select @my_param := 5)',)).all()[0]

The SQL that django then produces is:

SELECT `srvr_foo`.`id` 
FROM `srvr_foo` 
WHERE (5 = (select @my_param := 5))  
LIMIT 1;

Upvotes: 1

Related Questions