第一章 【Django开发入门】ORM的增删改查和批量操作
第二章 【Django开发入门】ORM查询分页以及返回Json格式
我们都知道Django框架默认是通过ORM来实现数据的增删改查,涉及到的orm方法为create、delete、update、get、filter、all、get_or_create、update_or_create。在Django中还有批量操作,如批量创建和批量更新,涉及到的方法为bulk_create、bulk_update。
日常开发过程中,都是以json格式来进行前后端数据传输。
models.py文件
class Users():
***
class Meta:
verbose_name = u'用户'
verbose_name_plural = verbose_name
def get_dict(self):
one_dict = {
'username':self.username,
'email':self.email,
****
}
return one_dict
views.py文件
from .models import Users
def get_one_project(request):
position = Project_position.objects.get(id=id)
return HttpResponse(json.dumps(position.get_dict()), content_type="application/json")
def get_all(request):
projectposition_list= Project_position.objects.all()
positionlist = []
for item in projectposition_list:
# print(item.level)
content = {}
content['岗位编号'] = item.id
content['岗位名称'] = item.project_position
content['定编人数'] = item.numberofpeople
content['实际人数'] = item.realitypeople()
content['使用状态'] = item.get_state_display()
content['岗位基本描述'] = item.describe
positionlist.append(content)
res = {}
res['status'] = 'success'
res['data'] = positionlist
return JsonResponse(res)
from django.forms.models import model_to_dict
def get_one_project(request):
position = Project_position.objects.get(id=id)
result= model_to_dict(position)
return HttpResponse(json.dumps(result), content_type="application/json")
def get_users(request):
users = UserProfile.objects.all()
result = serializers.serialize("json", users)
return HttpResponse(result)
下面这样也是可以的
import json
def get_users(request):
data = json.dumps(list(UserProfile.objects.all().values()))
return HttpResponse(data)
DRF是django前后端分离的三方库,具体使用可参考相关文档,DRF官方文档
DRF的使用需要配置相关参数,需要建立serializer.py文件。这里提供一份样例。
# -*- coding:utf-8 _*-
"""
@author:lenovo
@file: serializer.py
@time: 2022/11/4 9:50
"""
import re
from django.core.cache import cache
from django.core.validators import EmailValidator
from django.utils.translation import gettext as _
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from users.models import LoginUser
class RegisterSerializer(ModelSerializer):
"""注册账户"""
password = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)
code = serializers.IntegerField(write_only=True)
default_error_messages = {
"username_error": _('用户名必须以字母开头,且包含3~15个字母、数字'),
"username_registered_error": _('用户名已存在'),
'password_error': _('两次输入密码不一致'),
"phone_error": _('手机号格式有误,请重填'),
"phone_registered_error": _('手机号已注册'),
'code_error': _('验证码不正确'),
"email_error": _('电子邮箱格式有误,请重填'),
"email_registered_error": _('邮箱已注册'),
}
class Meta:
model = LoginUser
fields = ['username', 'phone', 'password', 'password2', 'code']
def validate_username(self, username):
"""单字段验证:名字"""
# 1.用户名格式
if not re.match(r'^[a-zA-z]\w{2,15}$', username):
raise serializers.ValidationError(self.error_messages['username_error'])
# 2.用户名是否存在
if LoginUser.objects.filter(username=username).exists():
raise serializers.ValidationError(self.error_messages['username_registered_error'])
return username
def validate_phone(self, phone):
"""单字段验证:手机号"""
# 1.验证手机号码是否合法
rs = r'^([+]?0?\d{2,3}-?|\([+]?0?\d{2,3}\)|\([+]?0?\d{2,3}\))?\d+$|^([+]?0?\d{2,3}-?|\([+]?0?\d{2,3}\)|\([+]?0?\d{2,3}\))?[1-9]\d{4,10}(-\d{1,10})?$'
if not re.match(r'1[0-9]\d{9}$', str(phone)) and not re.match(rs, str(phone)):
raise serializers.ValidationError(self.error_messages['phone_error'])
# 2.手机是否注册
if LoginUser.objects.filter(phone=str(phone)).exists():
raise serializers.ValidationError(self.error_messages['phone_registered_error'])
return phone
# def validate_code(self, code):
# """单字段验证:验证码"""
# phone =
# if cache.has_key(phone):
# old_code = cache.get(phone)
# print(str(code))
# print(1111)
# print(str(old_code))
# if str(old_code) != str(code):
# raise serializers.ValidationError(self.error_messages['code_error'])
def validate_email(self, email):
"""单字段验证:邮箱"""
# 1.邮箱格式
rs = '^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
if not re.match(rs, email):
raise serializers.ValidationError(self.error_messages['email_error'])
# 2.邮箱是否存在
if LoginUser.objects.filter(email=email).exists():
raise serializers.ValidationError(self.error_messages['email_registered_error'])
return email
def validate(self, attrs):
"""组合字段验证"""
password = attrs.get('password')
password2 = attrs.get('password2')
if password and password2 and password != password2:
raise serializers.ValidationError(self.error_messages['password_error'])
attrs['password'] = make_password(attrs['password2']) # 还可以通过重写create方法加密密码
# 验证码
phone = attrs.get('phone')
code = attrs.get('code')
print('123123')
if cache.has_key(phone):
old_code = cache.get(phone)
print(str(code))
print(1111)
print(str(old_code))
if str(old_code) != str(code):
raise serializers.ValidationError(self.error_messages['code_error'])
else:
raise serializers.ValidationError(self.error_messages['code_error'])
del attrs['password2']
del attrs['code']
return attrs
class UserSerializer(ModelSerializer):
class Meta:
model = LoginUser
fields = ['username', 'phone', 'user_permissions']
以下是views文件
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from target.models import Target
from target.serializer import TargetSerializer
from utils.jwt_auth import IsAuthentication
from utils.pagination import FSNumberPagination
@method_decorator(csrf_exempt, name="dispatch")
class TargetView(ModelViewSet):
"""
list:获取存档订单全部记录
retrieve:获取一条
"""
queryset = Target.objects.all()
serializer_class = TargetSerializer
# 筛选类型
filter_backends = [OrderingFilter]
# 指定可排序字段以及默认排序字段
ordering_fields = ['id']
ordering = ['-id']
# 认证
authentication_classes = [IsAuthentication]
# 权限
permission_classes = []
# 配置分页器类
pagination_class = FSNumberPagination
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response({
'code': 0,
'msg': 'ok',
'data': serializer.data
})
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from target.models import Target
from target.serializer import TargetSerializer
from utils.jwt_auth import IsAuthentication
from utils.pagination import FSNumberPagination
@method_decorator(csrf_exempt, name="dispatch")
class TargetView(ModelViewSet):
"""
list:获取存档订单全部记录
retrieve:获取一条
"""
queryset = Target.objects.all()
serializer_class = TargetSerializer
# 筛选类型
filter_backends = [OrderingFilter]
# 指定可排序字段以及默认排序字段
ordering_fields = ['id']
ordering = ['-id']
# 认证
authentication_classes = [IsAuthentication]
# 权限
permission_classes = []
# 配置分页器类
pagination_class = FSNumberPagination
# 限流
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return Response({
'code': 0,
'msg': 'ok',
'count': queryset.count(),
'data': serializer.data
})
serializer = self.get_serializer(queryset, many=True)
return Response({
'code': 0,
'msg': 'ok',
'count': queryset.count(),
'data': serializer.data
})
本片只是针对数据的返回做了相关处理,涉及到json的具体内容需要根据实际场景使用。