[DRF] Serializing a field of type choice

55 views
Skip to first unread message

ezequia...@gmail.com

unread,
Jun 9, 2021, 7:13:14 PM6/9/21
to Django users
Hey guys

Could you help me with a Django Rest Framework question?

I have a field in my model that has possible input values, so I'm using the choices= attribute in my model.

I'm having difficulty serializing the return of this data in drf.

Could someone give me a hint on how best to implement this, please?

Sincerely
Hezekiah Rock

Lalit Suthar

unread,
Jun 10, 2021, 12:27:18 AM6/10/21
to django...@googlegroups.com
can I see that model field, I don't think any extra configuration is required for it

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b6cd89ca-06be-4d5d-bdd0-ba9cbb952e72n%40googlegroups.com.

ezequia...@gmail.com

unread,
Jun 10, 2021, 9:51:49 AM6/10/21
to Django users
Here is my attempt:

question_type = (
     (1, 'Discussion'),
     (2, 'Multiple Choice'),
     (3, 'Writing'),
     (4, 'Objective'),
     (5, 'True or False'),
     (6, 'Practice'),
)

model.py
class Question(models.Model):
    de_description = models.TextField(max_length=255)
    cd_type_of_question = models.IntegerField(blank=False, verbose_name='Tipo de Questão', choices=question_type )

serializers.py
class QuestionFullSerializer(serializers.ModelSerializer):  
    cd_type_of_question  = serializers.ListField(child=serializers.CharField())
    class Meta:
        model = Question
        fields = ('id', ' de_description', 'cd_type_of_question')

Nikeet NA

unread,
Jun 10, 2021, 10:47:37 AM6/10/21
to django...@googlegroups.com
You must me getting the keys of your choices rather than your choice text , you can override the field  with serializer method field  and return your text according to your choice key.  

ezequia...@gmail.com

unread,
Jun 10, 2021, 3:41:59 PM6/10/21
to Django users
I solved the problem using a SerializerMethodField.

Thank you anyone.

Reply all
Reply to author
Forward
0 new messages