gpt4 book ai didi

python - Django REST to_representation : Have serializer fields appear last

转载 作者:行者123 更新时间:2023-12-03 08:10:41 28 4
gpt4 key购买 nike

我有以下序列化器类:

class DataLocationSerializer(QueryFieldsMixin, serializers.ModelSerializer):

def create(self, validated_data):
pass

def update(self, instance, validated_data):
pass

class Meta:
model = MeasurementsBasic
fields = ['temp', 'hum', 'pres', 'co', 'no2',
'o3', 'so2']

def to_representation(self, instance):
representation = super().to_representation(instance)
representation['timestamp'] = instance.time_received

return representation

数据以 JSON 文件形式返回,结构如下:

{
"source": "ST",
"stations": [
{
"station": "ST1",
"data": [
{
"temp": -1.0,
"hum": -1.0,
"pres": -1.0,
"co": -1.0,
"no2": -1.0,
"o3": -1.0,
"so2": null,
"timestamp": "2021-07-04T21:00:03"
}
]
}
]
}

我怎样才能使时间戳出现在序列化器的字段之前?

最佳答案

创建一个新字典:

def to_representation(self, instance):
representation = super().to_representation(instance)
return {'timestamp': instance.time_received, <strong>**representation</strong> }

关于python - Django REST to_representation : Have serializer fields appear last,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70946556/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com