首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django REST to_representation:让序列化器字段出现在最后

Django REST to_representation:让序列化器字段出现在最后
EN

Stack Overflow用户
提问于 2022-02-01 19:39:50
回答 1查看 1.3K关注 0票数 2

我有以下序列化程序类:

代码语言:javascript
复制
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文件中返回,结构如下:

代码语言:javascript
复制
{
    "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"                  
                }
            ]
        }
    ]
}

如何使时间戳出现在序列化程序的字段之前?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-01 20:09:22

创建一本新词典:

代码语言:javascript
复制
def to_representation(self, instance):
    representation = super().to_representation(instance)
    return {'timestamp': instance.time_received, **representation }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70946556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档