简体   繁体   English

如何在Django QuerySet中编写原始SQL查询?

[英]How to write a raw SQL query in Django QuerySet?

I want to use following SQL query in Django but I was unable to use that after trying directly with raw SQL. 我想在Django中使用以下SQL查询,但在直接尝试使用原始SQL后我无法使用它。 The SQL works directly while executing on PostgreSQL query window but on Django did not work. SQL在PostgreSQL查询窗口上执行时直接工作但在Django上没有工作。

The SQL is to find immediate lower value before a number 22522. I would like to use that in QuerySet format or in raw SQL. SQL是在数字22522之前找到直接较低的值。我想在QuerySet格式或原始SQL中使用它。 Added SQL query below- 在下面添加了SQL查询 -

SELECT id, name, zip 
FROM region 
WHERE zip >= (SELECT max(zip) FROM region WHERE zip < 22522) 
AND zip <= (SELECT min(zip) FROM region WHERE zip>22522) 
ORDER BY zip ASC LIMIT 1

Here is the code which I tried to use in raw query format. 这是我尝试在原始查询格式中使用的代码。 I saw, any other simple SQL query inside the c.execute() print result data correctly. 我看到, c.execute()内部的任何其他简单SQL查询都正确打印结果数据。

from django.db import connection

with connection.cursor() as c:
    c.execute("SELECT id, name, zip FROM region WHERE zip>=(SELECT max(zip) 
    FROM region WHERE zip<22522) AND zip<=(SELECT min(zip) FROM region 
    WHERE zip>22522) ORDER BY zip ASC LIMIT 1")

    for row in c.fetchall():
        print(row[1])

In order to get the result back in QuerySet format you need to start with a Djano model, for example: 为了以QuerySet格式返回结果,您需要从Djano模型开始,例如:

class Person(models.Model):
    first_name = models.CharField(...)
    last_name = models.CharField(...)
    birth_date = models.DateField(...)

>>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
        print(p)

For more detail, visit the Django documentation at: Django Documentation 有关更多详细信息,请访问Django文档: Django Documentation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM