E
E
epolyak2020-08-12 19:52:36
Django
epolyak, 2020-08-12 19:52:36

Custom serialization in django-rest-framework - how to customize attribute name with value?

For example, there are classes:

class Person(models.Model):
    name = models.CharField()
    ....

class Document(models.Model):
   person = models.ForeignKey(Person, related_name='docs', ..)
   doc_type = models.CharField()
   doc_number = models.CharField()
   doc_seria = models.CharField()
   ...


what sterilizers should be written to get a picture of the following character:
{
  "Person": {
      "name": "Ivan Petrov",
      "passport": {
           "doc_numer": "123455",
           "doc_seria": "1234"
       },
      "zagran" : {
         "doc_number": "12543",
         "doc_seria": 1234543
  }
}


In other words, I want to get, as a result of serialization, instead of the docs value, a substitution of the attribute value of one of the fields of the associated Document entity

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-08-14
@tumbler

Since the response schema changes, it will not be possible to describe the list of fields through serializers.

Person = SerializerMethodField(method="get_person")

def get_person(obj):
    return {"name": ..., "passport": ...}

But in general it is better to redo the response scheme to the list of documents inside Person.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question