我具有以下设置:
我有一个基本的博客和文章关系,可以获取所有博客及其相关文章:
class BlogSerializer(serializers.ModelSerializer):
articles = ArticleSerializer(many=True, read_only=True)
class Meta:
model = Blog
fields = ('id', 'name', 'articles')
depth = 0
class BlogViewSet(ViewSetMixin, GenericAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
现在我想保持原样,但是:
调用列表视图(例如api / blogs)时,只应发送文章的ID,因此我将视图集扩展为:
class BlogViewSet(ViewSetMixin, GenericAPIView, ..):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
def get_serializer(self, *args, **kwargs):
# pseudo code
if self.context['request'].action == 'list':
serializer = super(BlogViewSet, self).get_serializer(*args, *kwargs)
serializer.fields['articles'] = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
serializer.is_valid()
return serializer
我只是想用PrimaryKeyRelatedField覆盖相应的 articles 字段,所以只有id才能发货。
但是我得到的结果是空的(根本没有博客和文章),我也不知道为什么...有什么想法或建议?
谢谢问候!
答案 0 :(得分:0)
尝试一下
# serializers.py
class BlogSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.context['view'].action == 'list':
self.fields['articles'] = ArticleSerializer(many=True, read_only=True)
articles = ArticleSerializer(many=True, read_only=True) # remove this line
class Meta:
model = Blog
fields = ('id', 'name', 'articles')
depth = 0 # remove this also....I don't think this is relevant here
# views.py
class BlogViewSet(ViewSetMixin, GenericAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
我在这里所做的是,我们 强制 ,通过重写将articles
字段更改/映射到串行器ArticleSerializer
> __init__()
方法,只要它是不是list
的查看操作就可以了。默认情况下,DRF将在此处采用 PrimaryKeyRelatedField
关系。
希望这会有所帮助!