当前位置:网站首页>General view, serializer
General view, serializer
2022-07-23 11:15:00 【ZXY_ lucky】
1.DRF View
Django REST framework Based on the Web Application development framework , Rapid development of REST API Interface application
Provide serializers , Help realize serialization and deserialization
Provide class view 、 The extension class 、 View set to simplify view writing
Provide filtration 、 Paging and other functions
Provide API Of Web Visual interface , Test interface
API agreement
- Use as much as possible https agreement , To compare safety
- Try to appear in the domain name api word
- Try to appear the version number in the path Such as : /v1/users/users/
- Try to use nouns in the path
- Use the request method To represent the operation of resources
- Concatenate query strings in the path , Realize data filtering 、 Pagination 、 Sort, etc
2. establish Django
django-admin startproject Project name
2.1 To configure settings
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # drf frame
'corsheaders',
'user'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':'localhost',
'PORT':3306,
'USER':'root',
'PASSWORD':'123123',
'NAME':'p6',
}
}
CORS_ORIGIN_WHITELIST = [
"http://localhost:8080",
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = ("*")
CORS_ALLOW_METHODS = ("*")
2.2 Create model classes
The model needs to add time and update time , For simplicity
Create parent class ----> Create other models that inherit from this parent
from django.db import models
# Create your models here.
class BaseModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
# Departmental table
class Department(BaseModel):
name = models.CharField(" Department name ",max_length=30)
def __str__(self):
return self.name
class Meta:
db_table = "department"
# Job list
class Duty(BaseModel):
name = models.CharField(" Job title ",max_length=30)
def __str__(self):
return self.name
class Meta:
db_table = "duty"
# The employee table
class Staff(models.Model):
SEX_CHOICE = (
(1,' male '),
(2,' Woman ')
)
name = models.CharField(" full name ",max_length=30)
sex = models.IntegerField(" Gender ",choices=SEX_CHOICE,default=1)
phone = models.CharField(" cell-phone number ",max_length=11)
email = models.EmailField(" mailbox ",max_length=60)
department = models.ForeignKey(Department,on_delete=models.CASCADE,verbose_name=' department ')
duty = models.ForeignKey(Duty,on_delete=models.CASCADE,verbose_name=' duty ')
def __str__(self):
return self.name
class Meta:
db_table = 'staff'
User This model class inherits django Packaged AbstractUser,
There is no mobile number on it , Last login time , So define yourself
# User Model class
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
class User(AbstractUser):
mobile = models.CharField(" cell-phone number ",max_length=11)
last_login = models.DateTimeField(" Last login ",default=timezone.now)
def __str__(self):
return self.username
class Meta:
db_table = "user"
notes : This model class must be migrated for the first time , Otherwise, an error will be reported
3. Serializer
3.1 Serialization definition :
Turn the model class object into a dictionary , And then pass by Response To json character string ----- serialize
3.2 Deserialization
Put the front end of json String passing Request object , Turn to dictionary or similar dictionary , Then it is transformed into the object of the model class through the serializer ----- Deserialization
3.3 Serializer
from rest_framework import serializers
from .models import *
# Department serializer
class DepartmentSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID",read_only=True)
# allow_null Is it empty allow_blank Allow null trim_whitespace Truncate the space on both sides
name = serializers.CharField(label=" Department name ",min_length=2,max_length=10,allow_null=True,
allow_blank=True,trim_whitespace=True)
class DutySerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID", read_only=True)
name = serializers.CharField(label=" Job title ", min_length=2, max_length=10, allow_null=True,
allow_blank=True, trim_whitespace=True)
# staff
class StaffSerializer(serializers.Serializer):
id = serializers.IntegerField(label="ID",read_only=True)
name = serializers.CharField(label=" Employee name ",min_length=2,max_length=10,allow_null=True,
allow_blank=True,trim_whitespace=True)
sex = serializers.IntegerField(label=" Gender ",default=1)
phone = serializers.CharField(label=' cell-phone number ',min_length=11,max_length=11,allow_null=True,allow_blank=True,
trim_whitespace=True)
# Foreign keys
# queryset Reverse query set Deserialization
department = serializers.PrimaryKeyRelatedField(queryset=Department.objects.all())
duty = serializers.PrimaryKeyRelatedField(queryset=Duty.objects.all())
# Serialized method fields
department_name = serializers.SerializerMethodField(read_only=True)
# obj Employee model class object
def get_department_name(self,obj):
# obj.department Department object
return obj.department.name
duty_name = serializers.SerializerMethodField(read_only=True)
def get_duty_name(self,obj):
return obj.duty.name
# data verification attrs The dictionary from the front
def validate(self, attrs):
# get data
name = attrs.get("name")
return attrs
def create(self, validated_data):
staff = Staff.objects.create(**validated_data)
return staff
# rewrite update Method
def update(self, instance, validated_data):
instance.name = validated_data.get("name")
instance.save()
return instance
Common field types
| Field | Field construction method |
|---|---|
| CharField | CharField(label=,min_length=2,max_length=10,allow_null=True,allow_blank=True,trim_whitespace=True) |
| IntegerField | IntegerField(label=“ID”,read_only=True) |
| PrimaryKeyRelatedField | PrimaryKeyRelatedField(queryset=Department.objects.all()) |
| SlugField | SlugField(max_length=50, min_length=None, allow_blank=False) Regular fields , Verify the regular pattern [a-zA-Z0-9-]+ |
| DecimalField | DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: The maximum number of digits decimal_palces: Decimal place |
| TimeField | TimeField(format=api_settings.TIME_FORMAT, input_formats=None) |
| ImageField | ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
Option parameters
| Parameter name | effect |
|---|---|
| max_length | Maximum length : Output the maximum length check when deserializing |
| min_lenght | Minimum length : Input minimum length check during deserialization |
| allow_blank/allow_null | Is it allowed to be empty : Blank strings are allowed during deserialization , Not allowed by default |
| trim_whitespace | Truncate left and right white space characters , The default is True |
| max_value | minimum value : Check the input maximum value in the inverse sequence |
| min_value | Maximum : Input minimum value check during deserialization |
General parameters
| Parameter name | effect |
|---|---|
| read_only | This field is only used for serializing output , Default False |
| write_only | Indicates that this field is only used for deserializing input , Default false |
| required | Indicates that the field must be entered in deserialization , Default True |
| default | Use the default value when deserializing , If not specified , The default value when passing is 0 |
| allow_null | Indicates whether the field is allowed to pass in None, Default False |
| validators | Validator , Define your own functions , Realize complex data verification |
| label | be used for HTML Exhibition API When the page is , The name of the field displayed |
| help_text | be used for HTML Exhibition API When the page is , Field help prompt information displayed |
| error_messages | A dictionary containing error numbers and information |
a key :
- read-only: Display when serializing output , However, no verification is performed during deserialization verification
- write_only: Check during deserialization , However, this field is not output during serialization
3.4 ModelSerializer
class DepartmentModelSerializers(serializers.ModelSerializer):
class Meta:
model = Department
fields = '__all__'
read_only_fields = ["id",]
class DutyModelSerializers(serializers.ModelSerializer):
class Meta:
model = Duty
fields = '__all__'
read_only_fields = ["id",]
class StaffModelSerializers(serializers.ModelSerializer):
department_name = serializers.SerializerMethodField(read_only=True)
def get_department_name(self,obj):
return obj.department.name
duty_name = serializers.SerializerMethodField(read_only=True)
def get_duty_name(self,obj):
return obj.duty.name
class Meta:
model = Staff
fields = "__all__"
read_only_fields = ["id",]
and Serializer Difference
- Automatically generate a series of fields based on the model class
- Automatic generation based on model classes validators
- Default implementation update() and create() Method , You don't have to rewrite it
边栏推荐
猜你喜欢

MySQL statement queries all child nodes of a level node

【uiautomation】键指令大全(以及三种调用方式)+常用鼠标动作+SendKeys+Inspect学习

大厂面试机器学习算法(0):特征工程 | 数据预处理

RPC与thrift入门

Fundamentals of software testing - design method of test cases

开发必备之Idea使用

idea中复制一个项目/project

机器学习零散笔记:一些概念和注意

Spark常见面试问题整理
![[flink]flink on yarn之flink-conf最简单配置](/img/de/0ec23f3379148dba27fe77dc51e22f.png)
[flink]flink on yarn之flink-conf最简单配置
随机推荐
使用pytorch实现基于VGG 19预训练模型的鲜花识别分类器,准确度达到97%
【无标题】
【无标题】
SPR:SUPERVISED PERSONALIZED RANKING BASED ON PRIOR KNOWLEDGE FOR RECOMMENDATION
Partial usage of C #
p5面试题
初识Flask
十年架构五年生活-02第一份工作
[metric]使用Prometheus监控flink1.13org.apache.flink.metrics
Install enterprise pycharm and Anaconda
从零开始的pytorch小白使用指北
牛客刷题记录--Mysql
ShardingSphere分库分表方案
MySQL-8.0.28 用户操作 or 用户权限操作
Hyperlink de underlined code
MySQL statement queries all child nodes of a level node
shell/sh/bash的区别和基本操作
3. Threads in flask
Spectral clustering | Laplace matrix
Data Lake: introduction to Apache iceberg