处理字段配置的序列化程序,具有来自视图集的多个操作。
drf-action-serializer的Python项目详细描述
操作序列化程序
来源:https://github.com/gregschmit/drf-action-serializer
PYPI:https://pypi.org/project/drf-action-serializer/
action serializer是一个django rest框架扩展包,它提供了 实现每个操作字段配置的序列化程序,用于 DRF驱动的API。
问题:在构建api时,通常需要不同的序列化程序 不同的操作,例如列表视图与详细视图上的字段较少。正常情况下 必须构建多个序列化程序才能支持此操作。
解决方案:此应用程序提供ModelActionSerializer,它允许 您可以轻松配置每个操作的序列化。
如何使用
$ pip install drf-action-serializer
在序列化程序中,从action_serializer.ModelActionSerializer继承。
在序列化程序中,可以将action_fields字典添加到Meta 类并在操作下使用fields、exclude和extra_kwargs。 钥匙。此项目中的示例演示如何呈现 列表视图与详细视图的属性。
fromdjango.contrib.auth.modelsimportGroupfrom.serializersimportModelActionSerializerclassGroupActionSerializer(ModelActionSerializer):""" An example serializer for the Django ``Group`` model with details, and the list view has less fields than the detail. """classMeta:model=Groupfields=('id','name','permissions')action_fields={'list':{'fields':('id','name'),},}
在您的视图集中,只需像normal一样设置序列化程序:
fromrest_framework.viewsetsimportModelViewSetclassGroupViewSet(ModelViewSet):""" An example viewset for the Django ``Group`` model. """serializer_class=GroupActionSerializerqueryset=Group.objects.all()
测试
$ python manage.py test