I have a few models with a structure similar to this:
class YearInSchool(Enum):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
@classmethod
def choices():
return (tuple(i.name, i.value) for i in YearInSchool)
class Student(models.Model):
year_in_school = models.CharField(
max_length=2,
choices=YearInSchool.choices(),
)
class MyModel(models.Model):
# Some other fields here
year = models.ForeignKey(Student, blank=True, null=True, on_delete=models.SET_NULL)
The View I am using looks something like this:
class GetStudentDetails(generics.RetrieveUpdateDestroyAPIView):
class StudentSerializer(serializers.Modelserializer):
class Meta:
model = Student
fields = '__all__'
queryset = Student.objects.all()
serializer_class = StudentSerializer
lookup_field = 'year_in_school'
If I made an API call the result would look something like this:
{
// Some other fields here
"year": 1,
}
Instead I would like to receive the currently selected option as well as the available options. Something like this for a GET request:
{
// Some other fields here
"year": {
"selected": 'FR',
"choices": {
"FRESHMAN": 'FR',
"SOPHOMORE": 'SO',
"JUNIOR": 'JR',
"SENIOR": 'SR',
"GRADUATE": 'GR',
},
},
}
If I wanted to have the options returned from the API call as well, I would have to add an additional field like the one described in this post: https://stackoverflow.com/a/54409752/15459291
If I wanted the value of the currently selected choice instead of the primary key, I would also have to flatten the structure by adding another new field.
"The Browsable API" from the Django REST Framework shows all this information and implements drop-down selectors for choice fields that have the currently selected value preselected.
To me this seems like the most sensible way to present this information and make it available to the user. Someone somewhere already did all the work.
Is there a way for me to get all the necessary information I need in order to implement this functionality from one API call without having to go to the trouble of adding all these fields to my serializers for potentially hundreds of fields across several models?