Dynamically modifying serializer fields in Django Rest Framework(在 Django Rest Framework 中动态修改序列化器字段)
问题描述
我正在尝试使用 django rest 框架文档中描述的高级序列化程序用法.http://django-rest-framework.org/api-guide/serializers.html#advanced-serializer-usage 动态修改序列化器字段
I'm trying to use the Advanced serializer usage described in the django rest framework documentation. http://django-rest-framework.org/api-guide/serializers.html#advanced-serializer-usage to dynamically modifying serializer field
这是我的序列化程序类:
Here is my serializer class:
class MovieSerializer(serializers.ModelSerializer):
moviework_work = MovieWorkSerializer(many=True)
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
dropfields = kwargs.pop('dropfields', None)
# Instantiate the superclass normally
super(MovieSerializer, self).__init__(*args, **kwargs)
if dropfields:
# Drop fields specified in the `fields` argument.
banished = set(dropfields)
for field_name in banished:
self.fields.pop(field_name)
class Meta:
model = Movie
fields = ('field1','field2','moviework_work')
这是我的观点
class MovieFromInterpreterViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
serializer_class = MovieSerializer(dropfields=('moviework_work',))
我收到此错误:
TypeError: 'MovieSerializer' object is not callable
推荐答案
请注意,您设置的 serializer_class
不是类,而是类的实例.您要么需要将 dropfields
设置为类的属性,(就像在您链接到的文档示例中为 fields
所做的那样),或者您需要查看覆盖视图集的 get_serializer
方法(docs).
Note that you are setting serializer_class
not to a class, but to an instance of the class. You either need to set dropfields
as an attribute on the class, (just like it does for fields
in the documented example you link to) or you need to look at overriding the get_serializer
method of the viewset (docs).
这篇关于在 Django Rest Framework 中动态修改序列化器字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Django Rest Framework 中动态修改序列化器字段
基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01