How to get specific fields from child serializers?

django rest framework nested serializer post
drf serializer
serializermethodfield
primarykeyrelatedfield queryset
relatedfield.to_representation() must be implemented for field
django rest framework nested serializer foreign key
django rest framework many to-many
django serializer required fields

Say, there are two models:

class Model1(models.Model):
    r = models.CharField(max_length=200)

class Model2(models.Model):
    p = models.CharField(max_length=200)
    m = models.ForeignKey(Model1,on_delete=models.CASCADE)

The serializers are :

class Model1Serializer(serializers.Serializer):
    class Meta:
        model = Model1
        fields = '__all__'

class Model2Serializer(serializers.Serializer):
    class Meta:
         model = Model2
         fields = '__all__'

The given Model1 serializer returns the output as: { "id": 1, "r": "r_value" }

and model 2 serializer output is: { "id":1, "p: "p_value", "m": 1 }

The thing is that I also want the r value in the model2 serializer output. How to do that?

You need to specify new field with correct source - you can read more in docs.

Option 1: With class Serializer:
class Model2Serializer(serializers.Serializer):
    id = serializers.IntegerField()
    p = serializers.CharField()
    r = serializers.CharField(source='m.r')

    class Meta:
         model = Model2
         fields = '__all__'

Output: {'p': u'pppp', 'r': u'rrrrr', 'id': 1}

Option 2: With class ModelSerializer:
class Model2Serializer(serializers.ModelSerializer):
    r = serializers.CharField(source='m.r')

    class Meta:
         model = Model2
         fields = '__all__'

Output: {'p': u'pppp', 'r': u'rrrrr', 'm': 1L, u'id': 1}

Option 3: To include whole Model1:
class Model1Serializer(serializers.ModelSerializer):
    class Meta:
        model = Model1
        fields = '__all__'

class Model2Serializer(serializers.Serializer):
    m = Model1Serializer()

    class Meta:
        model = Model2
        fields = '__all__'

Output: {'m': OrderedDict([(u'id', 1), ('r', u'rrrrr')])}

Django Rest Framework Serializer Relations: How to get list of all , Got AttributeError when attempting to get a value for field `children` on serializer ` ParentSerializer`. The serializer field might be named� The drf-compound-fields package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the many=True option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.

Try this

class Model1Serializer(serializers.Serializer):
   class Meta:
      model = Model1
      fields = '__all__'

class Model2Serializer(serializers.Serializer):
  r = Model1Serializer(many=True, source="model1_set")
  class Meta:
     model = Model2
     fields = '__all__'

Serializer fields, When using the ModelSerializer class, serializer fields and relationships will be in order to explicitly specify how the child relationships should be saved. scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) The ListField class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField()

DRF makes it quite easy if you already have a Model1Serializer for Model1:

class Model2Serializer(serializers.Serializer):
    m = Model1Serializer()
    class Meta:
         model = Model2
         fields = '__all__'

That should be it.

Serializer relations, You can specify custom field-level validation by adding .validate_<fieldname> methods to your Serializer� Up to Django 1.7 included Options.get_field would return a FieldDoesNotExist when requested a GenericForeignKey field. However Django 1.8a1 has changed that and get_field now does return it. If you are interested in fixing this I can provide a test case against Django test suite. Context: I started working on the Django REST Framework port to

1. If you want r as attrs of m

define Serializer class of specific Relational Field

class Model2Serializer(serializers.ModelSerializer):
    m = Model1Serializer()
    class Meta:
        model = Model2
        fields = '__all__'

output:

[
    {
        "id": 1,
        "m": {
            "id": 1,
            "r": "RED"
        },
        "p": "Light RED"
    },
    {
        "id": 2,
        "m": {
            "id": 1,
            "r": "RED"
        },
        "p": "Dark RED"
    }
]
2. If you want just r Using ReadOnlyField

You can use ReadOnlyField

class Model2Serializer(serializers.ModelSerializer):
    r = serializers.ReadOnlyField(source='m.r')

    class Meta:
        model = Model2
        fields = '__all__'

output:

[
    {
        "id": 1,
        "r": "RED",
        "p": "Light RED",
        "m": 1
    },
    {
        "id": 2,
        "r": "RED",
        "p": "Dark RED",
        "m": 1
    }
]
3. If you want just r Using SerializerMethodField()

You can you SerializerMethodField and ist read only as well

class Model2Serializer(serializers.ModelSerializer):
    r = serializers.SerializerMethodField()

    class Meta:
        model = Model2
        fields = '__all__'

    def get_r(self, instance):
        return instance.m.r

output:

[
    {
        "id": 1,
        "r": "RED",
        "p": "Light RED",
        "m": 1
    },
    {
        "id": 2,
        "r": "RED",
        "p": "Dark RED",
        "m": 1
    }
]

Serializers, Simple model serializers that are vastly easier to understand and debug, and that It takes a child keyword argument which is used to specify the field used to� Note: The relational fields are declared in relations.py, but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers.<FieldName>.

Simply use depth=1 in your serializer Meta. Like this:

class Model2Serializer(serializers.Serializer):
    class Meta:
         model = Model2
         fields = '__all__'
         depth = 1

This will go for a level of 1 into the Foreign keys that do exist in that model. (By the way, I don't recommend it for big models. But it's perfectly suitable for your situation)

Serializers - Django REST framework, Make your code look like this django-rest framework has this amazing… Uses nested serializers for detailed view of children elements. Retrieve The external providers will send the data in a specific json format: UpdateOdds: There is an update for the odds field (all the other fields remain unchanged). Any child serializer can be expanded, not just Django model relations. A common use case for expanding fields may also be to avoid the large overhead from the serialized result, or to avoid unnecessarily computing time-consuming fields. Multiple child expansion

3.0 Announcement - Django REST framework, And we want to return a response when a particular parent is retrieved via API. For this purpose, we implement the corresponding serializers like this: class Meta: model = Child fields = ('url','id','child_name','parent_id') def create(self,� For efficiency reasons you end up creating multiple serializers, each with a very specific task. This can quickly grow out of hand, and lead to inconsistencies. We can solve this by using expandable fields. Here's how we could modify the serializers above to advantage of them:

Build a RESTAPI using nested serializers in Django-Rest , child – A field instance that should be used for validating the values in the dictionary. Now that you have a file called serializers in your project, let's create a� For example self.fields['asdf'] = serializers.CharField(). I assume the fields have already been evaluated when bind is called. Doing it in the fields property doesn't seem great either, since that thing is called a lot, and due to the lazy evaluation it has a caching mechanism in self._fields that would have to be duplicated in the concrete

django-rest-framework, Django rest-framework passes extra context data to serializers for the best design of rest applications. we can use "context" parameter in serializers to pass extra context. In viewsets, generic view simply override or overload the method get_serializer_context.

Comments
  • Please mark correct answer as accepted.