Harry
Harry

Reputation: 13329

Showing a related fields attribute

How would I do this to show the ForeignKey protected_area's name field?:

class NotificationReceiverSerializer(serializers.ModelSerializer):
    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area__name')

So now its just showing as PK, as expected:

protected_area":1

Upvotes: 1

Views: 27

Answers (1)

e4c5
e4c5

Reputation: 53754

Try something like this.

class NotificationReceiverSerializer(serializers.ModelSerializer):
    proteced_area = serializers.ReadOnlyField(source="protected_area.name")

    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area')

This will show the protected_area names as a read only field. Alternatively,

class NotificationReceiverSerializer(serializers.ModelSerializer):
    proteced_area = ProtectedAreaSerializer(read_only=True, many=True)

    class Meta:
        model = NotificationReceiver
        fields = ('pk','cellphone', 'protected_area')

to show all the fields in the related model

Upvotes: 2

Related Questions