table of Contents
drf- deserializer appreciated
Serializer effect
1. parity data
2. Conversion of the data object
序列化: 模型类对象 -----> python字典 用于输出, 返回给前端使用
反序列化: 前端传送的数据 -------> 经过验证 -----> python的字典 用于输入 接受前端数据时使用
Serializer role: helping us to serialize, deserialize
to sum up
When developing REST API interface, we need to do in the view of the core of the matter is:
The serialized data format database distal required, and return;
The front end of the data transmitted deserialize class object model, and saved to the database .
In view of the development of the REST API, although data for each different view of a specific operation, but add, delete, change, implementation process of the basic routine, so this part of the code is written may be multiplexed simplified:
By: verification request data -> executed during deserialization -> Database Save -> Save Object Serialization and returns
Delete: to determine whether there is data to be deleted -> delete the database execution
Change: determining whether data to be modified exists - verification request data> -> performed during deserialization -> Database Save -> Save Object Serialization and returns
Charles: query the database -> serialize the data and returns
car_ser.is_valid(raise_exception=True)
如果校验没有通过,会自动跑异常反馈给前台,代码不会往下执行
Base table
Base table, is an abstract class.abstract = True
Is designed to be inherited to provide public fields, database migration does not complete itself
model中建立表关系,并设置基表abstract = True,公有的表字段继承表类即可
from django.contrib.auth.models import User
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
created_time = models.DateTimeField(auto_now_add=True)
class Meta:
# 基表,为抽象类.是专门用来被继承提供公有字段的,自身不会完成数据库迁移
abstract = True
class Book(BaseModel):
pass
class Publish(BaseModel):
pass
Off the table associated relationship
It will not affect the table with the query efficiency
It will increase the operating efficiency of contingency tables CRUD
Easy to reconstruct the late database table
Disadvantage in that: the database itself is not detected contingency table, prone dirty data, to avoid the creation of dirty data (dirty data management when necessary) by a strict logical
举例: A字段依赖于B字段,先插入A记录,该记录对应的B记录没产生,在没有关联的情况下,该操作可以实现,但是数据就是脏数据 接着再通过B数据添加,脏数据就得到处理了,反过来先操作B后操作A,更符合逻辑思维,一样可以执行 联表查询,不会有任何异常
Foreign key field attribute
1. Reverse Lookup related_name=
related_name=
Provided in the foreign key field name of the foreign key reverse query正向找 字段名 反向找 related_name值.
2. cascade relationship on_delete=
on_delete
The outer key must be provided to indicate to cascade(值为models.CASCADE)
django 1.x下,系统默认提供
django 2.x下,必须手动明确,值为models.CASCADE
CASCADE
default cascade例子:作者没,详情一定没,存在没意义
DO_NOTHING
foreign keys are not cascaded, assuming any process dependent on Table A Table B, B record deletion, Table A foreign key field is not例子:作者没,书还是作者写的 | 出版社没,书还是该出版社出版的
SET_DEFAULT
foreign key reset depends on the assumed value of Table A Table B, B record deletion, Table A foreign key field is set to default attribute set, it must meet thedefault=
property using例子:部门没,部门员工进入待定部门(注:部门表一定要有待定部门记录)
SET_NULL
foreign key to reset the assumed dependent on Table A Table B, B record deletion, Table A foreign key field is set to null, it must meet thenull=true
property using例子:部门没,部门员工进入未分组部门(注:关联部门表外键可以为空)
Note: many to many fields can not be set on_delete to cascade, cascading defaults
如果要处理级联关系,需要手动明确关系表,处理关系表中的多个外键.
Table 3. Relationship db_constraint=
db_constraint
The foreign key table associated with the control, indicates that the associated default is True, False indicates to unlink
'''
1)Book 和 Publish 一对多:外键在多的一方 Book
2)Book 和 Author 多对多:外键在查询频率高的一方 Book
3)Author 和 AuthorDetail 一对一:外键要根据实际需求建立在合理的位置 AuthorDetail
'''
class Book(BaseModel):
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=10,decimal_places=2)
publish = models.ForeignKey(to='Publish',related_name='books',db_constraint=False,on_delete=models.DO_NOTHING,null=True)
author = models.ManyToManyField(to='Author',related_name='books',db_constraint=False)
def __str__(self):
return self.name
class Publish(BaseModel):
name = models.CharField(max_length=64)
address = models.CharField(max_length=64)
class Author(BaseModel):
name = models.CharField(max_length=64)
class AuthorDetail(BaseModel):
mobile = models.CharField(max_length=64)
# 反向查询时,可以定义related_name='detail'属性,直接 .detail 查询到Author表数据
author = models.OneToOneField(to=Author,related_name='detail',db_constraint=False,on_delete=models.CASCADE)
Subsequence of
It can only be used in serialization
Field name must be the foreign key field
The outer key is associated with a plurality of data, the need to clear many = true
# 出版社群查
class PublishAPIView(APIView):
def get(self,request,*args,**kwargs):
publish_query = models.Publish.objects.all()
# 序列化(群操作,many=true)
publish_ser = serializers.PublishModelSerializer(publish_query,many=True)
return Response({
'status':0,
'msg':'ok',
'results':publish_ser.data
})
# 多表操作
# 自定义的外键字段显示
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'
class PublishModelSerializer(serializers.ModelSerializer):
# 自定义序列化字段进行查询外键字段数据(出版社出版的书可能有多个,所以使用many)
books = BookModelSerializer(many=True)
class Meta:
model = models.Publish
# 所有字段
# fields = '__all__'
# 查询具有外键的字段
fields = ['name','address','books']