从序列化程序中删除不需要的字段的方法
drf_lighten的Python项目详细描述
DRF变亮
目的
即使我们在多个地方调用同一个端点,我们想要的信息 从反应上看差别很大。drf light使得可以指定和 只得到你想要的数据。
安装
pip install drf_lighten
用法
# serializers.pyfromappimportmodelsfromdrf_lighten.serializersimportDynamicFieldsMixinfromrest_frameworkimportserializersclassUserSerializer(DynamicFieldsMixin,serializers.HyperlinkedModelSerializer)classMeta:model=models.Userfields="__all__"classProfileSerializer(DynamicFieldsMixin,serializers.HyperlinkedModelSerializer)user=UserSerializer(read_only=True)classMeta:model=models.Profilefields="__all__"# views.pyfromappimportmodelsfromdrf_lighten.viewsimportDynamicFieldsMixinfromrest_frameworkimportviewsets# …classProfileViewSet(DynamicFieldsMixin,viewsets.ModelViewSet):queryset=models.Profile.objects.all()serializer_class=serializers.ProfileSerializer
示例
https://localhost:8000/profiles/
[{"url":"https://localhost:8000/profiles/22/","picture":"https://localhost:8000/media/22.jpg","phone_number":"+251-911-11-11-11","user":{"url":"https://localhost:8000/users/22/","user_name":"jupi2142","email":"test@gmail.com","first_name":"Henock","last_name":"Tesfaye"},"posts":["https://localhost:8000/posts/77/","https://localhost:8000/posts/78/","https://localhost:8000/posts/79/","https://localhost:8000/posts/79/","https://localhost:8000/posts/99/"]}]
https://localhost:8000/profiles/?fields=["url", "picture", {"user": ["url", "username"]}]
[{"url":"https://localhost:8000/profiles/22/","picture":"https://localhost:8000/media/22.jpg","user":{"url":"https://localhost:8000/users/22/","user_name":"jupi2142"}}]
配置
如果要使用与提供的查询参数不同的查询参数,可以转到django项目的设置并执行此操作
DRF_LIGHTEN_INCLUDE='fields'DRF_LIGHTEN_EXCLUDE='exclude'