Categories
Python Answers

How to add a ChoiceField with Django Rest Framework?

Spread the love

Sometimes, we want to add a ChoiceField with Django Rest Framework.

In this article, we’ll look at how to add a ChoiceField with Django Rest Framework.

How to add a ChoiceField with Django Rest Framework?

To add a ChoiceField with Django Rest Framework, we can set the source argument of the field.

For instance, we write

class User(AbstractUser):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

to create a CharField in the User model.

Then we write

class UserSerializer(serializers.ModelSerializer):
    gender = serializers.CharField(source='get_gender_display')

    class Meta:
        model = User

to create the gender field in the UserSerializer to set the source argument to the 'get_gender_display' method.

get_gender_display is a method that’s automatically included with the User model.

Conclusion

To add a ChoiceField with Django Rest Framework, we can set the source argument of the field.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *