0

Consider the following serializer

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'account')
        depth = 1

The field account refers to a ForeignKey in MyModel and I want to expose some of the Account fields with this serializer but not all of them.

How do I specify that only account.name and account.email should be serialized?

1 Answer 1

1

You can do this by creating your own serializer to use as the nested serializer.

class AccountSerializer(serializers.ModelSerializer):

    class Meta:
        model = Account
        fields = ('name', 'email', )

You are better off with creating specialized serializers instead of relying on Django REST Framework to create them for you. By default, serializers that are automatically created contain all fields defined on the model.

class MyModelSerializer(serializers.ModelSerializer):
    account = AccountSerializer()

    class Meta:
        model = MyModel
        fields = ('id', 'account', )

You can find out more about nested serializers in the Django REST Framework documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Got it. It would be great to extend ModelSerializer to include that feature in Django REST framework though.
You would have to override how the nested serializer is generated, it'd end up being far more work that just creating a second (or third, or fourth...) serializer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.