django中提供了一个raw()方法来使用sql语句进行查询
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField(max_length=50)
Person.objects.raw('SELECT * FROM myapp_person')
# myapp为你的app的名称
使用translations将查询到的字段映射到模型字段
name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
如果你只想要第一条数据,可以这样使用
first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]
first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]
当数据库中的数据很多的时候,最好使用第二个方法
如果需要执行参数化查询,可以使用下面这个方法
lname = 'Doe'
Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
不使用raw()进行查询
from django.db import connection
def my_custom_sql(self):
with connection.cursor() as cursor:
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
如果要在查询中包含文字百分号,则要使用两个%
cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [id])