ManyToMany category字段--在django restframework中显示title而不是id

ogsagwnx  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(123)

ManyToMany category字段--在django restframework中显示title而不是id
型号

class Category(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50,null=False, unique=True) 
    def __str__(self):
        return self.title

class BlogPostModel(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True)
    category = models.ManyToManyField(Category, related_name='catitems')
    title = models.CharField(max_length=255)
    body = models.TextField()
    slug = models.SlugField(max_length=255,null=False, unique=True)
    background_image = models.ImageField(upload_to='post-images',blank=True)
    image1 = models.ImageField(upload_to='post-images',blank=True)
    image2 = models.ImageField(upload_to='post-images',blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.title

字符串
我想显示类别的标题而不是类别的id
串行化器

class PostSerializer(serializers.ModelSerializer):
    author = serializers.CharField(source='author.email', read_only=True)
    class Meta:
            model = BlogPostModel
            fields = ['author','category','title','body','slug','background_image','created_date']


这是我的代码的结果:

"category": [
            1,
            2,
            3
        ],


我想要这个:

"category": [
             Category title(1)،
             Category title(2)،
             Category title(3)
        ],

dy1byipe

dy1byipe1#

你可以为category创建一个单独的序列化器,如下所示:

class CategorySerializer(serializers.ModelSerializer):
    
   class Meta:
      model = CategoryModel

字符串
现在你可以像这样在PostSerializer中包含类别序列化器:

class PostSerializer(serializers.ModelSerializer):
    ...
    category = CategorySerializer(many=True)
    ...


另外,不要忘记执行prefetch_related以提高无论在何处调用序列化程序的性能。

nkcskrwz

nkcskrwz2#

你可以使用SlugRelatedField()来实现:可以对序列化程序进行以下更改:

class PostSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(many=True, slug_field='title', queryset=Category.objects.all())
    author = serializers.CharField(source='author.email', read_only=True)
    class Meta:
            model = BlogPostModel
            fields = ['author','category','title','body','slug','background_image','created_date']

字符串
DRF SlugRelatedField文档,供参考

相关问题