I have a model that uses a Django choices field, like this:
class Question(models.Model):
QUESTION_TYPES = (
(10,'Blurb'),
(20,'Group Header'),
(21,'Group Footer'),
(30,'Sub-Group Header'),
(31,'Sub-Group Footer'),
(50,'Save Button'),
(100,'Standard Question'),
(105,'Text-Area Question'),
(110,'Multiple-Choice Question'),
(120,'Standard Sub-Question'),
(130,'Multiple-Choice Sub-Question')
)
type = models.IntegerField(default=100,choices=QUESTION_TYPES)
I'm using Django Rest Framework to present this model as an API to an Angular web app. In my Angular web app, I want a combo box widget that drops down with all those choices. Not the integers, but the text choices, like "blurb", "standard question" and so on.
Now, I could hand code the combo box into the Angular app, but in the spirit of DRY, is it possible to write a DRF serializer that just returns those choices (ie the QUESTION_TYPES object), so I can populate the combo box with a ReST query?
And by "possible", I guess I mean "simple and elegant". And maybe I also mean "ReSTful". (Is it ReSTful to do it that way?)
Just wondering . . .
Thanks
John
I would probably try something like the following:
The following doesn't work as I thought it should
(Following was my original intuition on serializing a list of objects, but it did not work. I'm leaving it in here anyway, because it seems like it should work.)
Okay, so we have a way to access the strings on their own, now we just need to serialize them, and for that, I'd probably try to use the
ListField
in DRF3, which should support thesource
kwarg, I would think?The following does return a list of results
Fallback: use a
SerializerMethodField
:Demo:
if you use a
ModelViewSet
in combination with aModelSerializer
, theOPTIONS
request will return metadata that you can use to get the choice options.This will give you a response that includes the
actions
attribute, that might look something like this:You can iterate over the
choices
attribute onqtype
to get all of the available choices.To get more familiar with this topic you can read: Metadata
I accomplished this by making an API endpoint for the choices which only use the GET verb.
models.py
viewsets.py