Click " Python crawler and data mining " above to follow
Reply to " Books " to receive a total of 10 e-books of Python from beginner to advanced
now
day
Chickens
soup
Qin Shiming Moon and Han Shiguan, Wanli Long March people have not returned.
Preface
Hey, friends, how to play this time, how to use Django to execute native SQL.
We all know that Python's handle in the web world-Django, can be described as a unified integration, a variety of plug-ins, forms components, model models, Admin backend, etc., I will give a special article later. , Anyway, it is a word, NB.
This time, let’s learn how to execute native statements in Django.
Cause
When using Django, under normal circumstances, we use Django's own model query is no problem, and can basically meet 80% of the problems
But, but, don’t you want 20%? It’s definitely not good, children only make a choice
There are three ways to execute native SQL in Django
extra
raw
django connection
Under normal circumstances, the above three methods
Table Structure
file:django_project/app01/models
class Book(models.Model):
title = models.CharField(verbose_name="书名", max_length=32)
describe = models.TextField(verbose_name="描述")
author = models.CharField(verbose_name="作者", max_length=32)
publisher = models.CharField(verbose_name="出版社", max_length=32)
publisher_date = models.DateField(verbose_name="publisher")
Is a very simple book list
Enter some data through admin to test use
extra way
It is strongly recommended, no need to learn, no use
raw way
Compared with extra, this is more useful.
The syntax is as follows
models.表名.objecs.raw(sql)
models.表名.objecs.raw(sql,[参数1,参数2])
Note: If there are no parameters, just write the sql statement. If there are parameters, you need to use a list later, as shown in the figure
For example
Returned still one Book object
The true native sql way
The above is actually some binding with django's model. But I mean, I just want native SQL, don't bind it to anything.
Here to talk about it, do not use pymysql to execute native sql in django, some strange problems will occur. Be sure to import and from django.db import connection
execute sql. code show as below:
from django.db import connection
def book_list(request):
# 真正的原生sql,
cursor = connection.cursor()
print(type(cursor))
cursor.execute("select * from app01_book where id=%s", [1, ])
raw = cursor.fetchall()
print(raw)
The returned content is shown in the figure below:
As you can see, what is returned is an array of sets in the list. I was thinking, is there any way to return the queried sql directly into a dictionary? The answer is of course!
Execute native sql and return to dict
I encapsulated the way of executing native sql and directly returning to a dictionary into two functions
One is to query multiple, the code is as follows:
def query_all_dict(sql, params=None):
'''
查询所有结果返回字典类型数据
:param sql:
:param params:
:return:
'''
with connection.cursor() as cursor:
if params:
cursor.execute(sql, params=params)
else:
cursor.execute(sql)
col_names = [desc[0] for desc in cursor.description]
row = cursor.fetchall()
rowList = []
for list in row:
tMap = dict(zip(col_names, list))
rowList.append(tMap)
return rowList
One is to query the other, the code is as follows:
def query_one_dict(sql, params=None):
"""
查询一个结果返回字典类型数据
:param sql:
:param params:
:return:
"""
with connection.cursor() as cursor:
if params:
cursor.execute(sql, params=params)
else:
cursor.execute(sql)
col_names = [desc[0] for desc in cursor.description]
row = cursor.fetchone()
tMap = dict(zip(col_names, row))
return tMap
The usage is as follows, call the function directly in the view
The returned result is as follows, directly in the list set dictionary format
What to do if the query is conditional, it is actually the same as pymysql
Return result
But there is a problem. In the above query, we clearly know that let only return one value, but it still returns a list set in a dictionary format. It doesn't seem right?
In fact, what I wrote above are two methods. If you are sure, you can query a value and use the query_one_dict
method.
Above summary
Native sql django performed in 3 ways, extra
, raw
,from django.db import connection
Which is extra
basically useless, raw
make do, but models
with binding, the connection
most flexible, but the default return is [tuple,tuple,tuple,] format
After improvement, the two packaging methods query_all_dict
, query_one_dict
a plurality of query, a single query, and returns to [dict, dict, dict,]
Suggest
Use only query_all_dict
,query_one_dict
Project code
django_exec_sql.zip
Friends who need the complete code of this article can reply to the keyword: native SQL in the background of this official account to get it.
to sum up
The above has been solved in an introductory way and arranged the following how to execute native sql through django.
Tell others with a smile that I am stronger than yesterday, and I will be the same in the future.
If you think the article is okay, remember to like and leave a comment to support us. Thank you for reading. If you have any questions, please remember to leave a message below~
If you want to learn more about Python, you can refer to the learning website: http://pdcfighting.com/, click to read the original text, you can go straight to it~
------------------- End -------------------
Recommendations of previous wonderful articles:
Teach you how to make a simple novel reader with Python
An article summarizes common operations on time in the Python library
Inventory of 5 personalized voice methods based on Python
Welcome everyone to like , leave a message, forward, reprint, thank you for your company and support
If you want to join the Python learning group, please reply in the background [ Enter the group ]
Thousands of rivers and mountains are always in love, can you click [ Looking ]
/Today's message topic/
Just say a word or two~~