[Answered ]-Combine models to get cohesive data

1👍

The thing you need to is to serialize the Contacts queryset to include the related User and UserPhoto objects for each contact.

Try to create a custom serializer for the Contacts model so:

class ContactSerializer(serializers.ModelSerializer):
    contact_user = serializers.SerializerMethodField()

    def get_contact_user(self, obj):
        user = obj.contact_user
        photo = user.userphoto_set.first()
        return {
            "id": user.id,
            "first_name": user.first_name,
            "url": photo.url if photo else None
        }

    class Meta:
        model = Contacts
        fields = ("contact_user",)

Then, modify the ContactViewSet to use this newly created serializer so:

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    
    def get_queryset(self):
        return Contacts.objects.filter(user__id=self.request.user.id)

Note: Generally, Django models don’t require s to be added as suffix since it is by default added, so it is better to modify it as Contact from Contacts.

Leave a comment