从序列化程序中删除不需要的字段的方法

drf_lighten的Python项目详细描述


DRF变亮

PyPI versionMaintainabilitypython3.xpython2.x

目的

即使我们在多个地方调用同一个端点,我们想要的信息 从反应上看差别很大。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'

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java我试图使用@OneToOne作为双向映射来映射实体,但却遇到了奇怪的异常   性能Java异步如何工作?异步方法似乎不是异步运行的   java这个代码可以更短吗   线程“main”Java中的csv Java ArrayList异常。lang.NegativeArraySizeException:28   java确定LayoutManager预布局中的显示视图   java如何在FirestorePagingAdapter中通过方法onLoadingStateChanged隐藏/显示进度条?   在Java中,如何打印一个类似于中间有“过道”的座位表的2d数组?   http Java实现字节范围服务,而不使用仅使用Java api的servlet   java无法使用命名根元素生成json   java如何在注销侦听器中获取http会话id?   数组内部输入(java)?   java如何为特殊情况提供更简单的构造函数   java在swing应用程序中显示JavaFX后台   java如何启用系统。出来在eclipse中运行Junit测试时使用println()?   如何在Java中实现Oracle用户定义的聚合函数