Reputation: 197
When I make a call to my API (curl), I get the following:
{"id": 1, "name": "Sword", "persona": [1]}
I'm getting the 'id' of the persona, but not the properties within. How do I do this?
Models.py:
class Persona(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
icon = models.CharField(max_length=255,default='1')
def __str__(self):
return self.name
class Equipment(models.Model):
personas = models.ManyToManyField(Persona)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
Serializers.py:
class EquipmentSerializer(serializers.ModelSerializer):
personas = serializers.PrimaryKeyRelatedField(queryset=Persona.objects.all(), many=True)
name = serializers.CharField(max_length=255)
class Meta:
model = Equipment
fields = ('id', 'name', 'persona')
Upvotes: 1
Views: 72
Reputation: 23134
You need two steps:
Create a Persona serializer class
:
class PersonaSerializer(serializers.ModelSerializer):
class Meta:
model = Persona
Then you can "chain" this serializer to the Equipement
one:
class EquipmentSerializer(serializers.ModelSerializer):
personas = PersonaSerializer(source='personas', many=True)
name = serializers.CharField(max_length=255)
class Meta:
model = Equipment
fields = ('id', 'name', 'personas')
For a deeper understanding of the above, have a look at this exemplary answer:
How do I include related model fields using Django Rest Framework?
Good luck :)
Upvotes: 1