[Django]-Get reverse relation in Django Serializer

2๐Ÿ‘

โœ…

A straightforward way to solve this is to use a SerializerMethodField like this:

class EMaterialRequestTableListSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(read_only=True, slug_field='full_name')
    transaction_no = serializers.SerializerMethodField()

    class Meta:
        model = MaterialRequest
        exclude = ('flows',)

    def get_transaction_no(self, obj)
        allotment = obj.allotment_set.first()
        return allotment.transaction_no if allotment else None

But this will try to hit the database per MaterialRequest instance just to get the related allotments.

To make this more efficient, you can prefetch the related allotments of each material request like this:

items = MaterialRequest.objects.all().order_by('-id').prefetch_related('allotment_set')

And then do something like this in your serializer:

class EMaterialRequestTableListSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(read_only=True, slug_field='full_name')
    transaction_no = serializers.SerializerMethodField()

    class Meta:
        model = MaterialRequest
        exclude = ('flows',)

    def get_transaction_no(self, obj)
        if obj.allotment_set.all():
            return obj.allotment_set.all()[0].transaction_no
        return None
๐Ÿ‘คBrian Destura

Leave a comment