drf-extra-fields icon indicating copy to clipboard operation
drf-extra-fields copied to clipboard

Introduce ConsciousChoiceField and LazyChoiceField

Open itsdkey opened this issue 3 years ago • 1 comments

I would like to introduce 2 fields that I think can have a good impact on this repo

  1. ConsciousChoiceField

This field can be used in situations where we want to force a user to pick an option. Let's say we have a model:

class Poll: choice = models.IntegerField(chocies=[(1, 'test'), (2, 'bar')])

and a serializer:

class PollSerializer(serializers.ModelSerializer): choice = ConsciousChoiceField(choices=[(1, 'test'), (2, 'bar')]))

DRF by default does not insert a blank choice as an option because the model's field says that a choice must be picked. So DRF sets the widget to the available options. But in this scenario, a user can just skip the field and leave the first option that was picked. In some situations, we don't want that - we want a clear, conscious choice.

  1. LazyChoiceField

This field can be used if we want to generate choices each time a serializer is loaded. In my mind, there are lots of scenarios. Firstly: when we want to query the database to get some available options. Secondly: if we want to ask a 3rd party API for our choices. Thirdly: when we want to load some options based on a keyword argument (for example a user's age/country/postcode).

If someone has some questions I'm willing to answer them :smiley:

itsdkey avatar Mar 10 '21 18:03 itsdkey

Hi, thank you for these fields.

Sorry, but I couldn't understand the use case of these fields. In these cases, I think we should we Django forms instead of DRF.

This package is mainly designed for JSON inputs and outputs. As far as I understand you use it as HTML.

gokselcoban avatar Jun 27 '22 15:06 gokselcoban