django - 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
]
}
]
解决方案
您可以简单地使用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']
推荐阅读
- git - BitBucket/Git - 创建一个新文件 + 合并到 master
- python - 比较熊猫数据框中的布尔值
- ios - 通过通话发送验证码是否被视为 VOIP 功能?
- django - 我可以在 django-compressor 标签中包含 Django 模板标签吗?
- react-native - 如何设置反应原生导航标题菜单?
- python-3.x - 需要在运行时根据表中存在的行数形成一个xpath定位器
- javascript - 如何防止在 puppeteer 的 chromium 实例中创建新选项卡?
- html - SVG 圆的样式在 Firefox 中不起作用,浏览器删除了半径属性
- gradle - 没有 sonar.language 属性无法工作
- android - A/B 测试订阅定价和免费试用效果