![](/img/trans.png)
[英]django-rest-framework how to make model serializer fields required
[英]Display fields based on the request in django-rest-framework serializer
我的 Django 项目中有一个帖子 model。 我想在用户收到帖子列表时显示description
字段,当他收到帖子实例时,显示body
字段。 (这两个字段分别存在于模型中)
这是我的 Post 序列化程序:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'image', 'description', 'slug']
lookup_field = 'slug'
这是我的观点:
class posts(viewsets.ModelViewSet):
queryset = Post.published.all()
serializer_class = PostSerializer
lookup_field = 'slug'
我想当用户在/posts/
url 中获得帖子列表时,看到如下内容:
[
{
"id": 31,
"title": "hello-world",
"image": { ... },
"description": "post description",
"slug": "hello-world"
},
...
]
当得到一个帖子实例时,看到这样的附加body
字段并排除description
字段:
{
"id": 31,
"title": "hello-world",
"image": { ... },
"body": "post body ...",
"slug": "hello-world"
}
我建议您使用不同的序列化程序,最好在不同的需求之间进行逻辑分离
class PostListSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'image', 'description', 'slug']
<...other attributes here ..>
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'image', 'body', 'slug']
< ...other_attributes_here.. >
您可以根据操作将您的视图集修改为 select 序列化程序
class Posts(viewsets.ModelViewSet):
queryset = Post.published.all()
serializer_class = PostSerializer
lookup_field = 'slug'
def get_serializer_class(self):
serializer_map = {
'retrieve': PostSerializer,
'list': PostListSerializer
}
return serializer_map.get(self.action, PostSerializer)
这应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.