在django中,我可以在检索查询之前在前导码中设置一个变量吗? [英] In django, can I set a variable in a preamble before retrieving a queryset?

查看:107
本文介绍了在django中,我可以在检索查询之前在前导码中设置一个变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据用户定义的步长对数据点进行可变分组,我希望最小化与django进行对接的代码中的原始SQL数量。问题我可以在MySQL中创建参数参数吗? ,似乎是一个伟大的方式来创建一个参数化的视图,但它需要我以某种方式在主查询执行之前设置一个变量。

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.

因此,我将如何设置在查询之前执行任何查询之前的mysql连接中的参数值?如果我有模型 Foo ,我做的非常基本:

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

如何将以下内容作为前导码注入任何代码由django ORM发送到SQL编译器?

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;


推荐答案

我想我有一个解决方案适用于我目前的MySQL后端我相信它可能取决于未指定的评估顺序,并可能会在将来的版本更改中中断:

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]

django然后生成的SQL是:

The SQL that django then produces is:

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

这篇关于在django中,我可以在检索查询之前在前导码中设置一个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆