[Django]-Serializing joined tables in serializers rest framework

3👍

you can try such solution:

from rest_framework import serializers

class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = ('mobile_number',)


class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('account_number',)


class UserSerializer(serializers.ModelSerializer):
    userdetail = UserDetailSerializer()
    account = AccountSerializer()
    user = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('userdetail', 'account', 'user')

    def get_user(self, obj):
        return {
            'first_name': 'obj.first_name',
            'last_name': 'obj.last_name',
            'email': 'obj.email',
            }

Leave a comment