Fetch foreign key object instead of ID in React from Django API

Viewed 1331

I have a model in my Django API with a foreign key for the parent, which references itself. I've serialized the data and returned it in a viewset. It returns an object in which the parent field shows the parent ID as an int. However, I'm trying to get it to display the actual values of the parent instead (name and category), so that I can then render the relevant data in my React frontend app. I've listed my model, serializer and viewset below, along with the object it's returning that shows the parent and also the child with the parent ID in the parent field. Can anyone please help?

class ComponentModel(models.Model):
    name = models.CharField(max_length=50, blank=False)
    wattage = models.PositiveIntegerField(blank=True, null=True)
    category = models.CharField(max_length=13, choices=CATEGORY_CHOICES, blank=False)
    parent = models.ForeignKey(
        'self',
        blank=True,
        null=True,
        on_delete=models.CASCADE
    )

class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ComponentModel
        fields = ('id', 'name', 'wattage', 'category', 'parent')

class ComponentViewSet(viewsets.ModelViewSet):
    queryset = ComponentModel.objects.all()
    serializer_class = ComponentSerializer

[
    {
        "id": 1,
        "name": "AMD",
        "wattage": null,
        "category": "cpu",
        "parent": null
    },
    {
        "id": 5,
        "name": "760K",
        "wattage": 100,
        "category": "cpu",
        "parent": 1
    }
]
1 Answers

One way is to define a simpler serializer and then use that for the parent as such:

class ParentComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ComponentModel
        fields = ('name', 'category')


class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ComponentModel
        fields = ('id', 'name', 'wattage', 'category', 'parent')
    parent = ParentComponentSerializer(many=False)

You can also make them inherit via:

class BaseComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ComponentModel
        fields = ['name', 'category']


class ComponentSerializer(serializers.ModelSerializer):
    class Meta(BaseComponentSerializer.Meta):
        fields = BaseComponentSerializer.Meta.fields + ['id', 'wattage', 'parent']
    parent = ParentComponentSerializer(many=False)
Related