Alex Nikitin
Alex Nikitin

Reputation: 931

How to exclude fields from nested representation Django?

I have following UserSerializer class

class UserSerializer(serializers.ModelSerializer):


class Meta:
    model = User
    fields = ['id', 'persons']
    depth = 1

The depth option allows me generate nested representations

{
"id": 2,
"persons": [
    {
        "id": 1,
        "name": "Alex",
        "city": "Paris",
        "bio": "This is my bio",
        "phone_number": "9130095484",
        "age": 24,
        "height": 56,
        "weight": 54}
]

I don't need all fields in nested representation. How to exclude some fields but keep the depth option?

The PersonSerializer looks like this

class PersonSerializer(serializers.ModelSerializer):

comments = CommentSerializer(source='comment_set', many=True)
images = ImageSerializer(source='image_set', many=True)

class Meta:
    model = Person
    exclude = ('paid', 'register_date', 'purchase_date')

Upvotes: 0

Views: 325

Answers (1)

Andy
Andy

Reputation: 684

Create PersonSerializer with required fields and use it inside UserSerializer.

class PersonSerializer(serializers.ModelSerializer):
    # required fields here


class UserSerializer(serializers.ModelSerializer):
    persons = PersonSerializer()

    class Meta:
        model = User
        fields = ['id', 'persons']
        depth = 1

Upvotes: 2

Related Questions