Accessing Django 3 TextChoices via an exposed API endpoint?

Viewed 558

I am using Django 3.0.4 with Django REST Framework 3.11.0 where I have a models.py like:

from django.db import models

from model_utils.models import TimeStampedModel


class SampleModel(TimeStampedModel):
    class Options(models.TextChoices):
        FOO = "A"
        BAR = "B"
        BAZ = "C"

    name = models.CharField(default="", max_length=512)

    options = models.CharField(
        max_length=2,
        choices=Options.choices,
        default=Options.FOO
    )

I would like to be able to create an API endpoint to return a list of my TextChoices as a tuple. I have a React frontend where I want to create a <select> dropdown with my list of choices. If I can access the list of TextChoices via an API endpoint, I should be good to go.

path("api/sample/choices/", views.SampleChoicesListView.as_view(), name="sample_choices")

I'm not sure what my views.py needs to look like to make this work...

class SampleChoicesListView(generics.ListAPIView):
   pass
2 Answers

Return the SampleModel.Options.choices as Response in an APIView

from rest_framework.views import APIView
from rest_framework.response import Response

# other required imports

class SampleChoicesListView(APIView):
    def get(self, request):
        # SampleModel.Options.choices would return
        # [('A', 'Foo'), ('B', 'Bar'), ('C', 'Baz')]
        choices = SampleModel.Options.choices
        # format it into dictionary
        # choices = {choice[0]: choice[1] for choice in SampleModel.Options.choices}
        return Response(choices)

Add urlpattern to api urls

path("options/", views.SampleChoicesListView.as_view(), name="options"),

List structure:

list structure

Dictionary structure:

dictionay structure

It may be cleaner to instead make an OPTIONS request to the SampleModel endpoint which should enumerate the valid options for that field, and also saves you creating a separate endpoint just to list the options. DRF should handle this all for you.

Related