代码之家  ›  专栏  ›  技术社区  ›  Br0k3nS0u1

如何使用Django rest框架在序列化程序中显示query_集的值?

  •  0
  • Br0k3nS0u1  · 技术社区  · 2 年前

    # -------------------------------------------------------------
    #                   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)
    

    如图所示
    enter image description here


    1 回复  |  直到 2 年前
        1
  •  1
  •   JeremyBearimy    2 年前

    你试过实施吗 __str__

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