Reputation: 876
First time Python user here, coming from Javascript world. I'm able to retrieve my Model serialized to JSON from Django API and display it on the frontend written in React. But now I just added one more field priority
to the Model that has multiple choices and I struggle to get these choices to the frontend (I want to display them in a dropdown and update REST API). Migration was successful and I can select choices from the back end but on the frontend I just get the default value set from migrations. Here is my code right now:
models.py
class Todo(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
completed = models.BooleanField(default=False)
priority_choices = [
('High', 'High'),
('Medium', 'Medium'),
('Low', 'Low'),
]
priority= models.CharField(max_length=6, choices=priority_choices, default='Low') #new field
def __str__(self):
return self.title
serializers.py
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title', 'description', 'completed', 'priority')
views.py
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoSerializer
queryset = Todo.objects.all()
I just want the simplest solution, preferably to just update TodoSerializer(serializers.ModelSerializer)
class inside serializers.py so that it would all come from this one Model. Is that possible? Reading https://www.django-rest-framework.org/api-guide/fields/#choicefield is not clear for me whether I need to create a new class for the same Model just to retrieve ChoiceFields or if it's possible to do it all from one Class but whatever I try, I get syntax errors. Like I said, I'm very fresh to Python. Thanks.
Upvotes: 0
Views: 1135
Reputation: 998
You can accomplish this using a SerializerMethodField
class TodoSerializer(serializers.ModelSerializer):
priority_choices = serializers.SerializerMethodField()
def get_priority_choices(self, obj):
return [choice[0] for choice in Todo.priority_choices]
class Meta:
model = Todo
fields = ('id', 'title', 'description', 'completed', 'priority', 'priority_choices')
Upvotes: 1