除了CharField 以外,还要很多别的---》表模型中 ?models.CharField ?--->基本一一对应
如果跟 表模型中对不上:你统一用 ?CharField
字段 | 字段构造方式 |
---|---|
BooleanField | BooleanField() |
NullBooleanField | NullBooleanField() |
CharField | CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) |
EmailField | EmailField(max_length=None, min_length=None, allow_blank=False) |
RegexField | RegexField(regex, max_length=None, min_length=None, allow_blank=False) |
SlugField | SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+ |
URLField | URLField(max_length=200, min_length=None, allow_blank=False) |
UUIDField | UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" |
IPAddressField | IPAddressField(protocol=’both’, unpack_ipv4=False, **options) |
IntegerField | IntegerField(max_value=None, min_value=None) |
FloatField | FloatField(max_value=None, min_value=None) |
DecimalField | DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置 |
DateTimeField | DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None) |
DateField | DateField(format=api_settings.DATE_FORMAT, input_formats=None) |
TimeField | TimeField(format=api_settings.TIME_FORMAT, input_formats=None) |
DurationField | DurationField() |
ChoiceField | ChoiceField(choices) choices与Django的用法相同 |
MultipleChoiceField | MultipleChoiceField(choices) |
FileField | FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ImageField | ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ListField | ListField(child=, min_length=None, max_length=None) |
DictField | DictField(child=) |
CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
DateTimeField(format=api_settings.DATETIME_FORMAT)
IntegerField(max_value=None, min_value=None)
参数名称 | 说明 |
---|---|
read_only | 表明该字段仅用于序列化输出,默认False |
write_only | 表明该字段仅用于反序列化输入,默认False |
required | 表明该字段在反序列化时必须输入,默认True |
default | 反序列化时使用的默认值 |
allow_null | 表明该字段是否允许传入None,默认False |
validators | 该字段使用的验证器 |
error_messages | 包含错误编号与错误信息的字典 |
label | 用于HTML展示API页面时,显示的字段名称 |
help_text | 用于HTML展示API页面时,显示的字段帮助提示信息 |
修改文件夹名
修改项目名
能顺利运行,按照如下图操作
如果改了文件夹名,全局替换
Rename directory:只改文件夹的名字不改项目名
Rename project:该项目名
两个都需要去改
然后在配置
然后更改文件名后进行全局替换
publish_name表中不存在
publish_name = serializers.CharField(source='name')
sb_name是表模型中一个方法
name = serializers.CharField(source='sb_name')
book表中可以链表查询
publish=models.ForeignKey(to='Publish.name')
-方案一:在表模型中写,在序列化类中映射 (可以使用source)
# models.py
def publish_detail(self):
return {'name': self.publish.name, 'city': self.publish.city}
# serializer.py
publish_detail = serializers.DictField()
# 前端看到
"publish_detail": {
"name": "北京出版本是",
"city": "北京"
}
-方案二:在序列化类中写SerializerMethodField,必须配合一个方法 get_字段名,方法返回什么,前端就看到什么
# Serializer.py
publish_detail = serializers.SerializerMethodField()
def get_publish_detail(self, obj):
return {'name': obj.publish.name, 'city': obj.publish.city}
# 前端看到
"publish_detail": {
"name": "北京出版本是",
"city": "北京"
}
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.name
# def book_name(self):
# return self.name+'sb'
# def publish_detail(self):
# return {'name': self.publish.name, 'city': self.publish.city}
#
# def author_list(self):
# l = []
# for author in self.authors.all():
# l.append({'name': author.name, 'age': author.age})
# return l
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
def __str__(self):
return self.name
class AuthorDetail(models.Model):
telephone = models.BigIntegerField()
birthday = models.DateField()
addr = models.CharField(max_length=64)
class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
def __str__(self):
return self.name
class Meta:
verbose_name = '出版社'
verbose_name_plural = verbose_name
class BookView(APIView):
def get(self, request):
obj = Book.objects.all()
ser = BookSerializer(instance=obj, many=True)
'''
[
{
"name": "西游记",
"price": "66.00",
"publish_detail": {name:名字,city:城市},
"authors_list":[{name:名字,age:19}]
},
]
'''
return Response(ser.data)
### 定制返回字段
class BookSerializer(serializers.Serializer):
name = serializers.CharField()
price = serializers.CharField()
#### 定制返回字段---》方案一:在表模型中写方法,在序列化类中做映射
# publish_detail = serializers.CharField() # publish_detail 会映射表模型中 publish_detail方法,方法返回值是 字典,强行用CharField字符串接收
# publish_detail = serializers.DictField() # publish_detail 会映射表模型中 publish_detail方法,方法返回值是 字典,用DictField接收
# author_list = serializers.ListField()
###定制返回字段---》方案二:在序列化类中写 SerializerMethodField
# 只要写了这个字段类SerializerMethodField,必须配合一个方法:get_字段名,这个方法返回什么,前端这个字段就显示什么
publish_detail = serializers.SerializerMethodField()
def get_publish_detail(self, obj):
# 当前序列化到的book对象
return {'name': obj.publish.name, 'city': obj.publish.city}
author_list = serializers.SerializerMethodField()
def get_author_list(self, obj):
l = []
for author in obj.authors.all():
l.append({'name': author.name, 'age': author.age})
return l
book_name = serializers.SerializerMethodField()
def get_book_name(self, obj):
return obj.name + 'sb'
?
反序列化保存
使用同一个序列化类会出现
class BookSerializer(serializers.Serializer):
name = serializers.CharField() # 公共的
price = serializers.CharField() # 公共的
publish = serializers.IntegerField(write_only=True) # 只用来做反序列化
authors = serializers.ListField(write_only=True) # 只用来做反序列化
publish_detail = serializers.SerializerMethodField(read_only=True) # 只用来做序列化
author_list = serializers.SerializerMethodField(read_only=True) # 只用来做序列化
def get_publish_detail(self, obj):
return {'name': obj.publish.name, 'city': obj.publish.city}
def get_author_list(self, obj):
l = []
for author in obj.authors.all():
l.append({'name': author.name, 'age': author.age})
return l
def create(self, validated_data):
# {name,price,publish:1,authors:[1,2]}
authors = validated_data.pop('authors')
book = Book.objects.create(name=validated_data.get('name'), price=validated_data.get('price'),
publish_id=validated_data.get('publish'))
book.authors.add(*authors)
return book
def update(self, instance, validated_data):
# {name,price,publish:1,authors:[1,2]}
authors = validated_data.pop('authors')
validated_data['publish_id'] = validated_data.pop('publish')
for key in validated_data:
setattr(instance, key, validated_data[key])
instance.save()
# 先清空在放入
# instance.authors.clear()
# instance.authors.add(*authors)
# 直接存
instance.authors.set(authors)
return instance
class BookView(APIView):
def post(self, request):
ser = BookSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
class BookDetail(APIView):
def put(self, request, pk):
book = Book.objects.filter(pk=pk).first()
ser = BookSerializer(instance=book, data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)
else:
return Response(ser.errors)
urlpatterns = [
path('books/', views.BookView.as_view()),
path('books/<int:pk>/', views.BookDetail.as_view()),
]
?
之前写的序列化类,继承了serializers.Serializer,跟表没有必然联系
ModelSerializer跟表一一对应,以后基本需要重写create和update
### 继承ModelSerializer--->少写代码
class BookSerializer(serializers.ModelSerializer):
name = serializers.CharField(max_length=18,min_length=3) # 公共的
price = serializers.CharField() # 公共的
publish = serializers.IntegerField(write_only=True) # 只用来做反序列化
authors = serializers.ListField(write_only=True) # 只用来做反序列化
# 上述操作,通过 Meta实现了
# 扩写的字段,也要在fields注册
# 方式二:定制字段
publish_detail = serializers.SerializerMethodField(read_only=True) # 只用来做序列化
author_list = serializers.SerializerMethodField(read_only=True) # 只用来做序列化
def get_publish_detail(self, obj):
return {'name': obj.publish.name, 'city': obj.publish.city}
def get_author_list(self, obj):
l = []
for author in obj.authors.all():
l.append({'name': author.name, 'age': author.age})
return l
# 方式二:定制字段方式一
publish_detail = serializers.DictField(read_only=True)
author_list = serializers.ListField(read_only=True)
class Meta:
model = Book # 写了这两句,会把表模型中Book,所有字段映射过来
# fields='__all__'
fields = ['name', 'price', 'publish', 'authors', 'publish_detail', 'author_list']
extra_kwargs = { # 给某个或某几个字段设置字段属性
'name': {'max_length': 18, 'min_length': 3},
'publish': {'write_only': True},
'authors': {'write_only': True},
'publish_detail': {'read_only': True},
'author_list': {'read_only': True},
}
# 一般不需要写create和update了---》ModelSerializer帮咱们实现了
# 局部钩子和全局钩子,该怎么写还怎么写
def validate_name(self,name):
pass