Kickasstimus
Kickasstimus

Reputation: 197

How do I get the whole JSON object in Django using DRF3?

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

Answers (1)

John Moutafis
John Moutafis

Reputation: 23134

You need two steps:

  1. Create a Persona serializer class:

    class PersonaSerializer(serializers.ModelSerializer):
        class Meta:
            model = Persona
    
  2. 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

Related Questions