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)
I want to replace the "Category object('number')" options by the choices of Category model(VIDEOGAMES, ANIME, MUSIC and CARTOONS).
CodePudding user response:
have you tried implementing __str__
in your model?
def __str__(self):
/*return what you want to display */