Search code examples
djangodjango-rest-frameworkdjango-serializer

Django Rest Framework Choices Field Serializer -- I'd like to get second element in a tuple


This is a model

class BookModel(models.Model):
    """The model to represent books."""

    class BookRating(models.IntegerChoices):
        AWFUL = 0, 'Awful'
        BAD = 1, 'Bad'
        NORMAL = 2, 'Normal'
        GOOD = 3, 'Good'
        GREAT = 4, 'Great'
        AWSOME = 5, 'Awesome'
     
    rating = models.PositiveSmallIntegerField(choices=BookRating.choices, null=True, blank=True)

And this is a serializer

Class BookSerializer(serializers.ModelSerializer):

     rating = serializers.ChoiceField(choices=BookModel.BookRating.choices, source='rating')

     class Meta:
         model = BookModel
         fields = '__all__'

How do I serialize it properly in my case? I saw the answer here were somone used a tuple of tuples and it worked with the logic I have, but idk how to do it when I use another class's choices for creating choices (sorry for tautology)


Solution

  • here's what i needed

    class BookSerializer(serializers.ModelSerializer):
        rating = serializers.CharField(source='get_rating_display')
    
        class Meta:
            model = BookModel
            fields = '__all__'