[Fixed]-Using ModelSerializer with joined records

1πŸ‘

βœ…

Is there a particular reason you need that extra() call? If the sole purpose of that call is to rename a field, you can omit that from the queryset and rename the field using a SerializerMethodField from your serializer. I will assume planeable is the ForeignKey field in BlockRepresentation model to the PlaneableItem model. Sample code:

from rest_framework import serializers

class BlockRepresentationSerializer(serializers.ModelSerializer):
    # Some fields
    name = serializers.SerializerMethodField()

    class Meta:
        model = BlockRepresentation

    def get_name(self, obj):
        if obj.planeable:
            return obj.planeable.name
        return ''
πŸ‘€Wannabe Coder

Leave a comment