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
}
]