Django Rest Framework - 过滤嵌套的序列化程序

时间:2017-09-24 15:37:54

标签: django-rest-framework

一本书可以有多种不同语言的BookContent。在我的例子中,该书有2个BookContents,一个用英语,另一个用中文。

我通过指定语言查询集来获取本书及其内容的特定语言:http://localhost/api/books/?language=english。当这是调用时,它调用views.py中的BookList get_query,我按语言过滤内容。但是,json结果仍会打印该书的所有BookContent。

以下是我的代码。

models.py

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)

class BookContent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    book = models.ForeignKey(Book, releated_name='content' on_delete=models.CASCADE)
    content = models.TextField()
    language = models.TextField()

serializers.py

class BookContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookContent
        fields = ('id', 'content', 'language')

class BookSerializer(serializers.ModelSerializer):
    content = BookContentSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = ('id', 'title', 'content')

views.py

class BookList(generics.ListAPIView):
    serializer_class = BookSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        if 'language' in self.request.query_params:
            language = self.request.query_params['language']
        return Book.objects.filter(content__language=language).distinct().order_by('title')

class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = (permissions.IsAuthenticated,)

目前的Json成绩:

{
    "results": [
        {
            "id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
            "title": "My Book Title",            
            "book_content": [
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
                    "content": "hello content 1",
                    "language": "english"
                },
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ed",
                    "content": "你好",
                    "language": "chinese"
                }
            ]
        }
    ]
}

如何仅获取特定语言的图书清单和BookContent语言?

预期Json成绩:

{
        "results": [
            {
                "id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
                "title": "My Book Title",            
                "book_content":
                    {
                        "id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
                        "content": "hello content 1",
                        "language": "english"
                    }

            }
        ]
    }

0 个答案:

没有答案