使用Django rest框架时更改字段名称 [英] Changing the field name when using Django rest framework
问题描述
我正在将序列化的数据从Django rest框架馈送到网站上的Javascript数据透视表。如果我有一个名为 created_on的变量,则DRF会将其用作字段名称。我想在数据透视表中显示的标签将被转换为创建时间。
I'm feeding serialized data from the Django rest framework to a Javascript pivot table on my site. If I have a variable called 'created_on', the DRF uses that as the field name. What I want to display in my pivot table is the label which will be converted to 'Created On'.
例如,我从DRF发出的输出如下:
As an example, my output from DRF is the following:
[{"created_on": "2016-04-23"}, {"created_on": "2016-05-23"}]
我想要的是:
[{"Created on": "2016-04-23"}, {"Created on": "2016-05-23"}]
在不覆盖序列化过程的情况下是否有可能?
Is this possible without me overriding the serialization process?
推荐答案
否(当前)在不覆盖序列化过程的情况下是不可能的。
No, its not possible (currently) without overriding the serialization process.
为什么不可能?
这是因为您要用于 created_on
的备用名称包含空格,并且无法在序列化程序中定义包含空格的字段。另外,当前没有功能为序列化过程中使用的字段提供备用名称。
This is because the alternate name which you want to use for created_on
contains whitespace and its not possible to define a field in your serializer having whitespaces in it. Also, there is no functionality currently to provide alternate name for a field to be used in serialization process.
可能的解决方案:
您可以覆盖序列化程序的 to_representation()
方法,并在其中添加 Created On
键,其值等于 created_on
键的值。然后所有序列化的对象将包含一个键创建于
。
You can override the to_representation()
method of your serializer and there add a Created On
key having value equal to the value of created_on
key. Then all the serialized objects will contain a key Created On
.
class MySerializer(serializers.ModelSerializer):
...
def to_representation(self, obj):
primitive_repr = super(MySerializer, self).to_representation(obj)
primitive_repr['Created On'] = primitive_repr['created_on']
return primitive_repr
如果备用名不包含空格怎么办?
如果备用名之间没有空格,您然后可以将 SerializerMethodField()
与 source
参数一起使用。
Had the alternate name did not contain any spaces between them, you could then have used SerializerMethodField()
with source
argument.
您本可以执行以下操作:
You could have done something like:
class MySerializer(serializers.ModelSerializer):
alternate_name = serializers.SerializerMethodField(source='created_on')
class Meta:
model = MyModel
fields = (.., 'alternate_name')
这篇关于使用Django rest框架时更改字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!