【Django】Mysql数据库操作(增、删、改、查)
1 数据查询
数据查询共有三种函数:
- all():无筛选条件查询并获取全部数据,类似于SELECT * FROM TABLE。返回值为queryset对象,仅可以通过for循环遍历访问或切片后遍历。
- filter():查询并获取部分符合条件的数据,类似于SELECT * FROM TABLE WHERE <筛选条件>。返回值为queryset对象,仅可以通过for循环遍历访问或切片后遍历。
- get():查询符合条件的一条数据,返回值为数据对象,可以直接访问。
-
all()查询获取所有数据
from django.http import HttpResponse from django.shortcuts import render from apps.message_form.models import Message def message_form(request): all_messages = Message.objects.all() first_messages = Message.objects.all()[:1] # 切片 # 返回的是queryset对象,因此必须for遍历 for message in all_messages: print(message.name) print(first_message.name) return render(request, "message_form.html")
-
查看执行的sql语句
def message_form(request): first_messages = Message.objects.all()[:1] print(first_message.query) # 输出sql语句 return render(request, "message_form.html")
-
filter()条件查询查询操作
all_messages = Message.objects.filter(name="chaoql") # 返回的是queryset对象,因此必须for遍历 for message in all_messages: print(message.email)
-
get()获取一个数据对象
def message_form(request): # get()查询不到数据或查询到多条数据,则抛出异常 try: message = Message.objects.get(name="chaoql1") print(message.address) except Message.DoesNotExist as e: pass except Message.MultipleObjectsReturned as e: pass return render(request, "message_form.html")
2 数据删除
-
删除get()到的数据对象
def message_form(request): try: message = Message.objects.get(name="chaoql1") print(message.address) message.delete() except Message.DoesNotExist as e: pass except Message.MultipleObjectsReturned as e: pass return render(request, "message_form.html")
-
删除all()和filter()到的queryset数据
要么for循环遍历后逐个删除,要么一次性全部删除。
def message_form(request):
all_messages = Message.objects.all()
for message in all_messages:
print(message.email)
message.delete() # 逐个数据对象删除
all_messages.delete() # 删除查询到的全部数据
return render(request, "message_form.html")
3 数据插入/更新
save():若数据存在则更新数据;若数据不存在则插入。(存在与否根据主键判别)
def message_form(request):
# 初始化数据对象并提交
message = Message()
message.name = "chaoql"
message.email = "1415331985@email.com"
message.address = "西安"
message.message = "无"
# 数据提交
message.save()
return render(request, "message_form.html")