mhyousefi
mhyousefi

Reputation: 1234

Conditionally nest Django serializers

So, I have a foreign key to my User model in many of my models. Now, the serializers for these models are nested, in that they include the entire user object rather than just the id. I have done so as shown bellow:

class BadgeSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Badge
        fields = '__all__'

It works as expected. However, I seldom find myself in a situation where I want just the id. I was wondering what is the best way to conditionally nest my BadgeSerializer...

Upvotes: 0

Views: 43

Answers (1)

mhyousefi
mhyousefi

Reputation: 1234

Now, the best solution I can think of is to have a non-nested BadgeSerializer, which includes only the user id. And then have a NestedBadgeSerializer (extending BadgeSerializer) which does nest the User model and include the entire user object.

class BadgeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Badge
        fields = '__all__'

class NestedBadgeSerializer(BadgeSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Badge
        fields = '__all__'

I am NOT sure if that's the proper way though.

Upvotes: 1

Related Questions