简体   繁体   中英

how to get specific field in serialiser with related_name by Django rest

i have model named ContactPhone and in the model link to Lead model with field lead_id and ralated_name phones

class ContactPhone(models.Model):
    phone_number = PhoneNumberField(blank=True, default='')
    phone_type = models.CharField(
        max_length=100,
        blank=True,
        choices=ContactPhoneInterface.phone_number_types,
        default=PhoneNumbers.mobile.name
    )
    contact_id = models.ForeignKey(
        Contact,
        on_delete=models.CASCADE,
        null=True,
        related_name='phones_c'
    )
    lead_id = models.ForeignKey(
        Lead,
        on_delete=models.CASCADE,
        null=True,
        related_name='phones'
    )

by this serilizer class i got id of ContactPhone table, but i need got phone_number field in ContactPhone.

class LeadListSerializer(serializers.ModelSerializer):

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

tried different options to solve this problem but it doesn't help. In the screenshot you can see response of this moment, id of ContactPhone

在此处输入图片说明

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',
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM