1

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
2
  • where are you getting values list? is it from other model? Commented Jan 2, 2021 at 14:55
  • 2
    Given the fact you already have the information in "entry" you shouldn't need it in "values". Now to do what you want, take a look at django-rest-framework.org/api-guide/fields/#listfield Commented Jan 2, 2021 at 15:20

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!. I think this might just do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.