Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show a value with query_set in a serializer using Django rest framework?

I am making an API and want to list all choices of a model for who use it.

# -------------------------------------------------------------
#                   Image category serializer
# -------------------------------------------------------------


class ImageCategorySerializer(serializers.ModelSerializer):
    
    #category = CategorySerializer()
    category = serializers.PrimaryKeyRelatedField(
        source="category.category",
        many=True,
        queryset=Category.objects.all(),
    )
    image = serializers.IntegerField(source="image.id")
    
    class Meta:
        fields = '__all__'
        model = ImageCategory


# -------------------------------------------------------------
#                           Category
# -------------------------------------------------------------


class Category(models.Model):
    """
    This model define a category

    Args:
        category (datetime): creation date
        created_at (str): description of the image
    """


    class CategoryChoice(models.TextChoices):
        """
        This inner class define our choices for several categories
    
        Attributes:
            VIDEOGAMES tuple(str): Choice for videogames.
            ANIME tuple(str): Choice for anime.
            MUSIC tuple(str): Choice for music.
            CARTOONS tuple(str): Choice for cartoons.
        """
        
        VIDEOGAMES = ('VIDEOGAMES', 'Videogames')
        ANIME = ('ANIME', 'Anime')
        MUSIC = ('MUSIC', 'Music')
        CARTOONS = ('CARTOONS', 'Cartoons')


    category = models.CharField(max_length=15, choices=CategoryChoice.choices, null=False, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)

This is shown
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to replace the "Category object(‘number’)" options by the choices of Category model(VIDEOGAMES, ANIME, MUSIC and CARTOONS).

>Solution :

have you tried implementing __str__ in your model?

def __str__(self):
   /*return what you want to display */ 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading