1. source用法
序列化器内的使用 book_name = serializers.CharField(max_length=8, min_length=3,source='name')
可以是字段,可以跨表,甚至可以是方法
class BookSerializer(serializers.Serializer): name_detail = serializers.CharField(max_length=8, min_length=3,source='name') # 或 publish_name = serializers.CharField(max_length=8, min_length=3,source='publish.name') # 或 xx = serializers.CharField(max_length=8, min_length=3,source='xx') #source的xx表示表模型中得方法
2. 定制序列化字段
2.1 serializerMetthodsField
publish = serializers.SerializerMethodField()
def get_publish(self, obj): # obj 是当前序列化的对象 return {'name': obj.publish.name, 'city': obj.publish.city, 'email': obj.publish.email}
SerializerMethodField必须配合一个方法(get_字段名,需要接受一个参数),方法返回什么,这个字段就是什么
2,2 在模型表中写方法
def publish_detail(self): return {'name': self.publish.name, 'city': self.publish.city, 'email': self.publish.email} 在序列化中取 publish_detail=serializers.DictField()
完整代码 ddd模型
models
class Book(models.Model):
name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish_date = models.DateField(null=True) publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE) authors = models.ManyToManyField(to='Author') # 写了个方法,可以包装成数据属性,也可以不包 def publish_detail(self): return {'name': self.publish.name, 'city': self.publish.city, 'email': self.publish.email} def author_list(self): res_list = [] for author in self.authors.all(): res_list.append({'id': author.id, 'name': author.name, 'age': author.age}) return res_list
序列化器
class BookSerializer(serializers.Serializer): name = serializers.CharField(max_length=8, min_length=3) price = serializers.IntegerField(min_value=10, max_value=99) publish_date = serializers.DateField() # 方式二:在表模型中写方法 publish_detail = serializers.DictField(read_only=True) # 练习,使用方式二实现,显示所有作者 author_list = serializers.ListField(read_only=True)
3. 有关联表的反序列化的保存,create方法
序列化字段和反序列化字段不一样
# 反序列化用的 publish = serializers.CharField(write_only=True) authors = serializers.ListField(write_only=True) #序列化用的 publish_detail = serializers.DictField(read_only=True) author_list = serializers.ListField(read_only=True)
序列化类中的create方法重写
def create(self, validated_data): # validated_data 校验过后的数据 {"name":"三国1演义", "price":19, "publish_date": "2022-09-27", "publish":1, "authors":[1,2] } book = Book.objects.create(name=validated_data.get('name'), price=validated_data.get('price'), publish_date=validated_data.get('publish_date'), publish_id=validated_data.get('publish'), ) authors = validated_data.get('authors') book.authors.add(*authors) return book
4.序列化器中的钩子函数
def validate_price(self,data): 局部钩子, # print(data) if float(data)>10: return data else: raise ValidationError('价格太低楼') def validate(self,data): 全局钩子 print(data) return data
5. 模型序列化器的使用
class BookModelSerializer(serializers.ModelSerializer): #ModelSerializer继承Serializer # 不需要写字段了,字段从表模型映射过来 ,在这也可以写字段 class Meta: model = Book # 要序列化的表模型 # fields='__all__' # 所有字段都序列化 fields = ['name', 'price', 'publish_date', 'publish', 'authors', 'publish_detail', 'author_list'] # 列表中有什么,就是序列化哪个字段 # 给authors和publish加write_only属性 # name加max_len属性 extra_kwargs = { 'name': {'max_length': 8}, 'publish': {'write_only': True}, 'authors': {'write_only': True}, } publish_detail = serializers.SerializerMethodField(read_only=True) ... author_list = serializers.SerializerMethodField(read_only=True) ...
标签:serializers,name,self,高级,publish,序列化,data,DRF From: https://www.cnblogs.com/so-shuai/p/17137470.html