[Answer]-Django rest_framework relations

1👍

Try:

class FooBarSerializer(serializers.ModelSerializer):
    class Meta:
        model = FooBar
        depth = 1

It looks like you are after nested serialization, where the serialized FooBar contains serialized representations of the Foo and Bar models. This will, in turn, serialize Foo and Bar with serializers.ModelSerializer.

If you need to customize serialization of Foo or Bar, you’ve done the right thing creating FooSerializer and BarSerializer classes. Now you need to attach them to FooBarSerializer, so try this:

class FooBarSerializer(serializers.ModelSerializer):
    foo = FooSerializer(required=False)
    bar = BarSerializer(required=False)

    class Meta:
        model = FooBar

Further reading:

  • depth attribute documentation
  • required=False with nesting documentation
  • Here’s the issue that allowed empty relations with nested serializers and it’s been in REST framework since 2.1.14.

Leave a comment