【问题标题】:Django REST to_representation: Have serializer fields appear lastDjango REST to_representation:序列化器字段最后出现
【发布时间】:2022-02-02 04:09:22
【问题描述】:

我有以下序列化程序类:

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"                  
                }
            ]
        }
    ]
}

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

【问题讨论】:

    标签: python django django-rest-framework django-serializer


    【解决方案1】:

    创建一个新字典:

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

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2015-04-03
      • 1970-01-01
      相关资源
      最近更新 更多