Home > Net >  Django get data in serializer from two steps away related table
Django get data in serializer from two steps away related table

Time:07-19

I have the below models:

class Campaign(Base):
    name = models.CharField(max_length=100, unique=True)
    display_name = models.CharField(max_length=100)

class SubTopic(Base):
    name = models.CharField(max_length=100, unique=True)
    display_name = models.CharField(max_length=100)


class CampaignSubTopicAssn(Base):
    campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE)
    subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn',on_delete=models.PROTECT)

    class Meta:
        unique_together = ('campaign', 'subtopic')
class CampaignSubTopicAssnSerializer(serializers.ModelSerializer):
    class Meta:
        model = org_models.ContextualCampaignSubTopicAssn
        fields = ['subtopic']

In my campaign serializer I want to fetch all the subtopic_ids and their display_name as well: currently this serializer just gives the ids and not the name, basically the table is two steps away in relation.

class CampaignSerializer(serializers.ModelSerializer):
    
    subtopic_assn = CampaignSubTopicAssnSerializer(many=True)

CodePudding user response:

You need to serialize the Subtopic fields and call it in your CampaignSubTopicAssnSerializer as shown below.

class CampaignSubTopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubTopic
        fields = ['id', 'name' ]

class CampaignSubTopicAssnSerializer(serializers.ModelSerializer):
    subtopic = CampaignSubTopicSerializer()
    class Meta:
        model = CampaignSubTopicAssn
        fields = ['subtopic' ]

This will give result as shown below. hope this is what you are expecting.

enter image description here

or you can try the below code :

class CampaignSubTopicAssnSerializer(serializers.ModelSerializer):
    subtopic_id = serializers.IntegerField(source='subtopic.id')
    subtopic_name = serializers.StringRelatedField(source='subtopic.name')
    class Meta:
        model = CampaignSubTopicAssn
        fields = ['subtopic_id','subtopic_name' ]

where you can change subtopic_id, subtopic_name as per your requirement

  • Related