Search code examples
djangodjango-rest-frameworkdjango-postgresql

DjangoRestFrameWork filter one model from another


I have a model with an ArrayField called "participants".

I can't have the array be a list of users due to the limitations of postgress' ArrayField. Due to this, I have stored the usernames as strings in the array.

Now I want to serialize the user ID, and username

class ConversationSerializer(serializers.ModelSerializer):
    class Meta:
        model = c.Conversation
        lookup_field = 'uid'
        fields = (
          'uid',
          'participants',
          'archived',
        )

Is there anyway I can return the user ID's of the participants instead of the strings? So instead of the below result:

{
    "uid": "dd51b07d-06f2-481a-b68d-fa18e9959392",
    "participants": [
        "userJohn", "userDave"
    ],
    "archived": false
}

I could get the user model fields:

{
    "uid": "dd51b07d-06f2-481a-b68d-fa18e9959392",
    "participants": [
        { 
            'username': 'userJohn',
             'id': 4,
        },
        { 
            'username': 'userDave',
             'id': 5,
        }

    ],
    "archived": false
}

Solution

  • serializermethodfield can help, and if you use standard user model, you can try:

    class ConversationSerializer(serializers.ModelSerializer):
        participants = serializers.SerializerMethodField()
        class Meta:
            model = c.Conversation
            lookup_field = 'uid'
            fields = (
              'uid',
              'participants',
              'archived',
            )
    
        def get_participants(self, obj):
             users = User.objects.filter(username__in=obj.participants)
             return users.values('id', 'username')
    

    more deatails read in serializermethodfield