首页 > 解决方案 > DRF ListAPIView 返回多对多值名称而不是 pk

问题描述

我有一个帖子模型包含标签字段,该字段具有 ManyToManyField 到类别模型,

当我调用 REST ListAPIView 所有帖子标签返回 pk 我试图覆盖 ListAPIView 中的列表函数并为每个帖子映射所有 tags_name 但这需要大量时间并破坏性能

我希望/相信这种情况下有内置的东西

模型.py

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=256)
    content = RichTextField()
    tags = models.ManyToManyField(Categories)

    def __str__(self):
        return self.title



class Categories(models.Model):
    tag_name = models.CharField(max_length=256, unique=True)

    def __str__(self):
        return self.tag_name

    class Meta:
        ordering = ('tag_name',)
        unique_together = ('tag_name',)

视图.py

from .models import Post
from .serializers import NewPostSerializer, PostSerializer


class NewPost(CreateAPIView):
    serializer_class = NewPostSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]


class PostList(ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

序列化程序.py

class NewPostSerializer(ModelSerializer):

    class Meta:
        model = Post
        fields = ['title', 'content', 'tags']

        read_only_fields = ['tags', 'author_id']

当我访问 ListApiView 链接返回的结果将是这样的:

[
    {
        "id": 30,
        "title": "post title test",
        "content": "lorem text",
        "author": 3,
        "tags": [
            8, # should be games
            3  # should be action
        ]
    }
]

标签: djangodjango-rest-frameworkdjango-serializer

解决方案


您可以简单地使用SlugRelatedField,这将返回名称列表而不是 pks 列表

from rest_framework import serializers
class NewPostSerializer(ModelSerializer):

    tags = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='tag_name'
    )
    class Meta:
        model = Post
        fields = ['title', 'content', 'tags']

        read_only_fields = ['author_id']

推荐阅读