Django序列化器,关键是我想要的值。

huangapple go评论74阅读模式
英文:

Django Serializers, the key is a value I want

问题

I can help you with the translation. Here is the content you provided in Chinese:

尝试序列化我从服务收到的请求,该请求是JSON格式,是一个包含子键/值集的键/值集,见示例。

城市包含一个名为streets的键,其中包含一个字典,字典中的键名是街道名称,我当然希望将其序列化出来。

我对Django Rest Framework相当新,不知道如何序列化这种数据,因为这类数据的文档有限。我无法更改传入的请求数据。

请求:

{
  "cityName": "Some name",
  "population": 5,
  "streets": {
    "theBestStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 200,
      "houses": 5000
    },
    "theWorstStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 7,
      "houses": 4
    }
  }
}

也许我需要以某种方式手动序列化它?

英文:

trying to serialiaze a request I get from a service, the request is JSON and it is a key/value set that contains sub key/value sets, see example.

The city contains a key named streets that has a dict where key name is the street name that I would of course want to serialize out.

I am quite new to Django rest framework and have no idea how to serialize this as there is limited documentation for this kind of data. I cannot change the incoming request data.

Request:

{
  "cityName": "Some name",
  "population": 5,
  "streets": {
    "theBestStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 200,
      "houses": 5000
    },
    "theWorstStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 7,
      "houses": 4
    }
  }
}

Maybe I need to serialize this manually in some way?

答案1

得分: 1

这段代码逐行解释其功能:

from rest_framework import serializers

class CitySerializer(serializers.Serializer):
    cityName = serializers.CharField()
    population = serializers.IntegerField()
    streets = serializers.DictField()

这段代码导入了必要的模块并定义了一个名为 CitySerializer 的序列化器类。它继承自 serializers.Serializer,这是Django REST框架(DRF)的一部分。

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['streets'] = {
        street_name: self._serialize_street(street_data)
        for street_name, street_data in instance.streets.items()
    }
    return representation
  1. to_representation 方法被重写以提供自定义的序列化对象表示。此方法在将对象转换为序列化格式(例如JSON)时调用。
  2. 它首先调用父类的 to_representation 方法,以获取对象的初始表示。
  3. 然后,通过将原始的 'streets' 值替换为每个街道的序列化表示来修改表示字典。
  4. instance.streets.items() 返回了实例的streets属性的字典视图,对其进行迭代以序列化每个街道的数据。
  5. 对于每个街道名和街道数据对,将调用 _serialize_street 方法以创建街道数据的序列化表示。
  6. 得到的带有序列化街道的字典赋值回表示 ['streets']

这是.py文件的内容:

from rest_framework import serializers

class CitySerializer(serializers.Serializer):
    cityName = serializers.CharField()
    population = serializers.IntegerField()
    streets = serializers.DictField()

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['streets'] = {
        street_name: self._serialize_street(street_data)
        for street_name, street_data in instance.streets.items()
    }
    return representation

def _serialize_street(self, street_data):
    return {
        'streetNumberStart': street_data['streetNumberStart'],
        'streetNumberEnd': street_data['streetNumberEnd'],
        'houses': street_data['houses']
    }

JSON格式:

{
  "cityName": "Some name",
  "population": 5,
  "streets": {
    "theBestStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 200,
      "houses": 5000
    },
    "theWorstStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 7,
      "houses": 4
    }
  }
}

希望这个解释有帮助。

英文:

Let's go through the provided code line by line to explain its functionality:

from rest_framework import serializers

class CitySerializer(serializers.Serializer):
  cityName = serializers.CharField()
  population = serializers.IntegerField()
  streets = serializers.DictField()

This code imports the necessary modules and defines a serializer class called CitySerializer. It inherits from serializers.Serializer, which is a part of the Django REST Framework (DRF).

def to_representation(self, instance):
representation = super().to_representation(instance)
representation['streets'] = {
    street_name: self._serialize_street(street_data)
    for street_name, street_data in instance.streets.items()
}
return representation
  1. The to_representation method is overridden to provide a custom
    representation of the serialized object. This method is called when
    converting the object to a serialized format, such as JSON.
  2. It first calls the parent class's to_representation method to get
    the initial representation of the object.
  3. Then, it modifies the representation dictionary by replacing the
    original 'streets' value with a serialized representation of each
    street.
  4. The instance.streets.items() returns a dictionary view of the
    streets attribute of the instance, which is iterated over to
    serialize each street's data.
  5. For each street_name and street_data
    pair, the _serialize_street method is called to create a serialized
    representation of the street data.
  6. The resulting dictionary, with serialized streets, is assigned back
    to the representation ['streets'].

The .py file:

from rest_framework import serializers

class CitySerializer(serializers.Serializer):
     cityName = serializers.CharField()
     population = serializers.IntegerField()
     streets = serializers.DictField()

def to_representation(self, instance):
   representation = super().to_representation(instance)
   representation['streets'] = {
    street_name: self._serialize_street(street_data)
    for street_name, street_data in instance.streets.items()
   }
return representation

def _serialize_street(self, street_data):
return {
    'streetNumberStart': street_data['streetNumberStart'],
    'streetNumberEnd': street_data['streetNumberEnd'],
    'houses': street_data['houses']
}

Json Format:

{
  "cityName": "Some name",
  "population": 5,
  "streets": {
    "theBestStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 200,
      "houses": 5000
    },
    "theWorstStreetName": {
      "streetNumberStart": 1,
      "streetNumberEnd": 7,
      "houses": 4
    }
  }
}

I hope this explanation helps

huangapple
  • 本文由 发表于 2023年5月11日 14:42:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定