赞
踩
BaseSerializer
是 Django REST framework (DRF) 中的一个核心类,用于将复杂的数据类型(如查询集和模型实例)转换为 Python 数据类型,以便于渲染成 JSON、XML 或其他内容类型。BaseSerializer
是所有序列化器的基类,提供了一些常用的方法和属性。以下是一些常用的方法和属性的介绍:
to_representation(instance)
def to_representation(self, instance):
return {
'id': instance.id,
'name': instance.name,
'email': instance.email,
}
to_internal_value(data)
def to_internal_value(self, data):
return {
'id': data.get('id'),
'name': data.get('name'),
'email': data.get('email'),
}
validate(attrs)
def validate(self, attrs):
if 'email' in attrs and not attrs['email'].endswith('@example.com'):
raise serializers.ValidationError("Email must be from the domain 'example.com'.")
return attrs
create(validated_data)
def create(self, validated_data):
return MyModel.objects.create(**validated_data)
update(instance, validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.email = validated_data.get('email', instance.email)
instance.save()
return instance
data
serializer = MySerializer(instance)
serialized_data = serializer.data
errors
serializer = MySerializer(data=request.data)
if not serializer.is_valid():
errors = serializer.errors
is_valid(raise_exception=False)
serializer = MySerializer(data=request.data)
if serializer.is_valid():
# Data is valid
else:
# Data is not valid
validated_data
serializer = MySerializer(data=request.data)
if serializer.is_valid():
validated_data = serializer.validated_data
initial_data
serializer = MySerializer(data=request.data)
initial_data = serializer.initial_data
下面通过一个具体的示例来展示如何在实际应用中使用 BaseSerializer
中的常用方法。假设有一个简单的 Django 模型 Book
,我们将创建一个序列化器 BookSerializer
来演示这些方法的实际用法。
首先定义一个简单的 Book
模型:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13, unique=True)
接下来定义一个 BookSerializer
,并在其中使用 BaseSerializer
的常用方法:
from rest_framework import serializers from .models import Book class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) author = serializers.CharField(max_length=100) published_date = serializers.DateField() isbn = serializers.CharField(max_length=13) def to_representation(self, instance): """将模型实例转换为原生 Python 数据类型""" return { 'title': instance.title, 'author': instance.author, 'published_date': instance.published_date, 'isbn': instance.isbn, } def to_internal_value(self, data): """将原生数据转换为验证后的数据""" return { 'title': data.get('title'), 'author': data.get('author'), 'published_date': data.get('published_date'), 'isbn': data.get('isbn'), } def validate(self, attrs): """对输入数据进行验证""" if len(attrs['isbn']) != 13: raise serializers.ValidationError("ISBN must be 13 characters long.") return attrs def create(self, validated_data): """使用验证后的数据创建并返回一个新实例""" return Book.objects.create(**validated_data) def update(self, instance, validated_data): """使用验证后的数据更新并返回一个现有实例""" instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.published_date = validated_data.get('published_date', instance.published_date) instance.isbn = validated_data.get('isbn', instance.isbn) instance.save() return instance
将 Book
模型实例序列化为 JSON 格式:
from .models import Book
from .serializers import BookSerializer
# 假设我们有一个 Book 实例
book_instance = Book.objects.get(id=1)
# 序列化
serializer = BookSerializer(book_instance)
serialized_data = serializer.data
print(serialized_data)
将 JSON 数据反序列化为 Book
模型实例:
from .serializers import BookSerializer # 假设我们有一些 JSON 数据 json_data = { 'title': 'New Book', 'author': 'John Doe', 'published_date': '2023-10-01', 'isbn': '1234567890123' } # 反序列化 serializer = BookSerializer(data=json_data) if serializer.is_valid(): book_instance = serializer.save() print(book_instance) else: print(serializer.errors)
使用验证后的数据更新现有的 Book
实例:
from .models import Book from .serializers import BookSerializer # 假设我们有一个 Book 实例 book_instance = Book.objects.get(id=1) # 新的数据 update_data = { 'title': 'Updated Book', 'author': 'Jane Doe', 'published_date': '2023-10-02', 'isbn': '1234567890123' } # 更新 serializer = BookSerializer(book_instance, data=update_data) if serializer.is_valid(): updated_instance = serializer.save() print(updated_instance) else: print(serializer.errors)
验证输入数据:
from .serializers import BookSerializer
# 一些无效的 JSON 数据
invalid_data = {
'title': 'Invalid Book',
'author': 'John Doe',
'published_date': '2023-10-01',
'isbn': '1234567890' # ISBN 长度不正确
}
# 验证
serializer = BookSerializer(data=invalid_data)
if not serializer.is_valid():
print(serializer.errors) # 输出验证错误信息
好的,下面我将完善这个例子,假设有一个名为 StatPlatProjectData
的模型,并且我们希望在序列化时删除某些字段(如 created_at
、updated_at
和 executor
),将使用 BasicSerializer
作为基类,并在 to_representation
方法中自定义序列化逻辑。
首先定义 StatPlatProjectData
模型:
from django.db import models
class StatPlatProjectData(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
executor = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
接下来定义 StatPlatProjectDataSerializer
,并在其中使用 BasicSerializer
的常用方法:
from rest_framework import serializers from .models import StatPlatProjectData class BasicSerializer(serializers.ModelSerializer): pass class StatPlatProjectDataSerializer(BasicSerializer): created_at = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True) updated_at = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True) class Meta: model = StatPlatProjectData fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) del_keys = ['created_at', 'updated_at', 'executor'] for key in del_keys: data.pop(key, None) return data
将 StatPlatProjectData
模型实例序列化为 JSON 格式,并删除指定的字段:
from .models import StatPlatProjectData
from .serializers import StatPlatProjectDataSerializer
# 假设有一个 StatPlatProjectData 实例
project_data_instance = StatPlatProjectData.objects.get(id=1)
# 序列化
serializer = StatPlatProjectDataSerializer(project_data_instance)
serialized_data = serializer.data
print(serialized_data)
在这个例子中,serialized_data
将包含所有字段,除了 created_at
、updated_at
和 executor
。
将 JSON 数据反序列化为 StatPlatProjectData
模型实例:
from .serializers import StatPlatProjectDataSerializer # 假设有一些 JSON 数据 json_data = { 'name': 'New Project', 'description': 'This is a new project.', 'executor': 'John Doe' } # 反序列化 serializer = StatPlatProjectDataSerializer(data=json_data) if serializer.is_valid(): project_data_instance = serializer.save() print(project_data_instance) else: print(serializer.errors)
使用验证后的数据更新现有的 StatPlatProjectData
实例:
from .models import StatPlatProjectData from .serializers import StatPlatProjectDataSerializer # 假设有一个 StatPlatProjectData 实例 project_data_instance = StatPlatProjectData.objects.get(id=1) # 新的数据 update_data = { 'name': 'Updated Project', 'description': 'This is an updated project.', 'executor': 'Jane Doe' } # 更新 serializer = StatPlatProjectDataSerializer(project_data_instance, data=update_data) if serializer.is_valid(): updated_instance = serializer.save() print(updated_instance) else: print(serializer.errors)
验证输入数据:
from .serializers import StatPlatProjectDataSerializer
# 一些无效的 JSON 数据
invalid_data = {
'name': 'Invalid Project',
'description': 'This is an invalid project.',
'executor': '' # executor 不能为空
}
# 验证
serializer = StatPlatProjectDataSerializer(data=invalid_data)
if not serializer.is_valid():
print(serializer.errors) # 输出验证错误信息
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。