0

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?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
M D
  • 19
  • 1
  • 6
  • Can you rephrase putting accent on the question? I am not quite sure what you are asking. What API calls are you making and what needs to be the response? – Sorin Burghiu Jun 26 '22 at 09:34
  • I would like to call GET, PUT and DELETE. I have updated my post with an example of what the return value for a GET request could be. I am not sure what is meant by "putting accent on the question". – M D Jun 26 '22 at 10:07

0 Answers0