[英]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.