admin管理员组文章数量:1400621
In the case of nested serializers, is there a way to specify a method that will get the data?
class AuthorSerializer(ModelSerializer):
....
class BookSerializer(ModelSerializer):
authors = AuthorSerializer(many=True)
....
In this example, I would like to intercept and modify how BookSerializer
gets the authors
. How do I accomplish this?
In the case of nested serializers, is there a way to specify a method that will get the data?
class AuthorSerializer(ModelSerializer):
....
class BookSerializer(ModelSerializer):
authors = AuthorSerializer(many=True)
....
In this example, I would like to intercept and modify how BookSerializer
gets the authors
. How do I accomplish this?
- So you want to filter these? – willeM_ Van Onsem Commented Mar 25 at 7:35
1 Answer
Reset to default 0If you want to filter, you typically don't do this in the serializer, but in the ViewSet
, like:
from django.db.models import Prefetch
from rest_framework import viewsets
class BookViewSet(ModelViewSet):
serializer_class = BoolSerializer
queryset = Book.objects.prefetch_related(
Prefetch('authors', Author.objects.filter(is_alive=True))
)
This will also boost performance significantly, because all Author
s are fetche in one additional query.
本文标签: djangoSpecifying get methods for nested serializersStack Overflow
版权声明:本文标题:django - Specifying get methods for nested serializers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744232975a2596426.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论