austin__abraham
austin__abraham

Reputation: 25

Creating a nested JSON from a value in Django Rest Framework

I'm very new to Django and the DjangoRest Framework and this is my first question on Stack overflow, please bear with me.

I am trying to create a Django Rest API that can that to handle entries for an online raffle. So each entry would have details like name, email, and a string that represents the raffle entry in the form of numbers separated by spaces(Eg: "12,23,34,45,56,67"). So far, I've been able to do the basics and create a simple model, serializer, and views.

What I need is to create a JSON similar to

{
    "entry" : "12,23,34,45,56,67",
    "name" : "SampleName",
    "email" : "[email protected]",
    "values" : [
        "one" : 12,
        "two" : 23,
        "three" : 34,
        "four" : 45,
        "five" : 56,
        "six" : 67
    ]
}

models.py

class EntryModel(models.Model):
    entry = models.CharField(null=False, max_length=17)
    name  = models.CharField(null=False, max_length=100)
    email = models.EmailField(null=False)

serializers.py

class EntrySerializer(serializers.ModelSerializer):

    class Meta:
        model = EntryModel
        fields = ['entry', 'name', 'email']

views.py

class EntryViews(viewsets.ModelViewSet):
    queryset = EntryModel.objects.all()
    serializer_class = EntrySerializer

Upvotes: 1

Views: 1626

Answers (1)

Adithya
Adithya

Reputation: 1728

I'm guessing you want the entry field to be expanded into values field.

In serializer, you can use a SerializerMethodField.

class EntrySerializer(serializers.ModelSerializer):
    values = serializers.SerializerMethodField()
    class Meta:
        model = EntryModel
        fields = ['entry', 'name', 'email', 'values']
    
    def get_values(self, obj):
        #here object is the EntryModel instance, you can access the entry field with obj.entry, transform into required format and return

Upvotes: 2

Related Questions