S
S
stayHARD2015-08-25 12:48:07
Django
stayHARD, 2015-08-25 12:48:07

How to add extra key to json?

Hello.
How can I slightly change the json structure what the serializer gives me?
Actually here it is:

class SectionSerializer(serializers.ModelSerializer):
  images = ImageSerializer(many = True, read_only = True)
  images2 = Image2Serializer(many = True, read_only = True)
  class Meta:
    model = Sections
    fields = ('id', 'name', 'audio1', 'audio2', 'images', 'images2')

I need the image2 field to be nested.
As a result, I want to get:
[
    {
        "id": 1,
        "name": "Lake1",
        "audio1": "qwe",
        "audio2": "qwe",
        "images": [
            {
                "id": 1,
                "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
                 "images2": [
                     {
                          "id": 1,
                          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
                     },
                    {
                          "id": 2,
                          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
                   }
        ]
    }
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav Dragalev, 2015-08-25
@vladqwerty

Upd. If you get an object as a result with a structure:

var obj = {
  "id": 1,
  "name": "Lake1",
  "audio1": "qwe",
  "audio2": "qwe",
  "images": [
    {
      "id": 1,
      "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
    }],
  "images2": 
    [
        {
          "id": 1,
          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
        },
        {
          "id": 2,
          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
        }
   ]
}

then doing
obj.images.images2 = obj.images2;
delete obj.images2;

get object with structure
{
  "id": 1,
  "name": "Lake1",
  "audio1": "qwe",
  "audio2": "qwe",
  "images": [
    {
      "id": 1,
      "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png",
      "images2": 
    [
        {
          "id": 1,
          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
        },
        {
          "id": 2,
          "file_name": "/images/66acc105-1c06-45aa-a3b8-5_S3USvg3.png"
        }
   ]
    }]
}

I
Ilya, 2015-08-25
@FireGM

Read about custom fields
www.django-rest-framework.org/api-guide/fields/#cu... See https://github.com/heywbj/django-rest-framework-re...
See examples in more detail https://github.com/heywbj/django-rest-framework-re... Namely, the implementation of NodeSerializer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question