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?

Share Improve this question asked Mar 24 at 18:49 David R.David R. 9459 silver badges17 bronze badges 1
  • So you want to filter these? – willeM_ Van Onsem Commented Mar 25 at 7:35
Add a comment  | 

1 Answer 1

Reset to default 0

If 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 Authors are fetche in one additional query.

本文标签: djangoSpecifying get methods for nested serializersStack Overflow