How to pull other serialized data from different Serializer classes?

I'm trying to pull the permissions data into my UserSerializer. I have a Many To Many relationship with User to Group with a through table called GroupUser. I'm able to pull the group_id and the group_name, but I can't seem to populate the data for permissions into my User Serializer. So far I've tried using permission = serializers.ReadOnlyField(source='group.permissions') but that doesn't work.

Any suggestions?

Here's my code:

class GroupSerializer(serializers.ModelSerializer):
    users = GroupUserSerializer(source='groupuser_set', many=True)
    permissions = PermissionSerializer(source='permission_set', many=True)
    class Meta:
        model = Group
        fields = ('id', 'name', 'users', 'permissions', 'role', )

class GroupUserSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='group.id')
    name = serializers.ReadOnlyField(source='group.name')
    class Meta:
        model = GroupUser
        fields = ( 'id', 'name', )

class UserSerializer(serializers.ModelSerializer):
     tests = TestSerializer(source='test_set', many=True)
     groups = GroupUserSerializer(source='groupuser_set', many=True)
     class Meta:
        model = User
        fields = ( 'id', 'username', 'groups', 'tests', )

I want my data to look like this:

    {
    "id": 1,
    "username": "user",
    "groups": [
        {
            "id": 2,
            "name": "employee"
            "permission": "Access-Denied"
        }
    ],
    "tests": []
},

but I have it without "permissions"

2 answers

  • answered 2018-01-11 22:03 tommyshere

    class UserSerializer(serializers.ModelSerializer):
         tests = TestSerializer(source='test_set', many=True)
         groups = GroupSerializer(read_only=True, many=True)
         class Meta:
            model = User
            fields = ( 'id', 'username', 'groups', 'tests', )
    

  • answered 2018-01-12 05:29 aircraft

    I recommend you to write a new Serializer for your UserSerializer, this will not affect other Serializers:

    class GroupForUserSerializer(serializers.ModelSerializer):
        users = GroupUserSerializer(source='groupuser_set', many=True)
        permissions = PermissionSerializer(read_only=True , many=True)
        class Meta:
            model = Group
            fields = ('id', 'name', 'permissions' )
    

    Then you can in your UserSerializer use GroupForUserSerializer now:

    class UserSerializer(serializers.ModelSerializer):
         tests = TestSerializer(source='test_set', many=True)
         groups = GroupForUserSerializer(source='groupuser_set', many=True)
         class Meta:
            model = User
            fields = ( 'id', 'username', 'groups', 'tests' )