[Answered ]-How to get specific field in serialiser with related_name by Django rest

1๐Ÿ‘

โœ…

If you want to return a list of specific fields from a related model you can use a serializers.SlugRelatedField

class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='phone_number'
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

EDIT: The ContactPhone.phone_number field is not serializable

One option is to set the __str__ method of the ContactPhone model to return the phone number and use a StringRelatedField

class ContactPhone(models.Model):
    ...

    def __str__(self):
        return str(self.phone_number)


class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.StringRelatedField(
        many=True,
        read_only=True,
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

Or adding a property that returns the string of phone_number to the ContactPhone model and using that in a SlugRelatedField is potential option

class ContactPhone(models.Model):
    ...

    @property
    def phone_number_str(self):
        return str(self.phone_number)


class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='phone_number_str'
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

Leave a comment