Django Rest框架在序列化程序中检索列表

时间:2019-01-16 22:16:34

标签: python django django-rest-framework

请考虑以下示例。我有两个模型,一个Author和一个Article。它们看起来像这样:

# author.py

from django.db import models


class Author(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return self.first_name
# article.py

from django.db import models
from authors.models import Author


class Article(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    text = models.TextField()

    def __str__(self):
        return self.text

我的序列化器如下所示:

from rest_framework import serializers
from .models import Article
from authors.serializers import AuthorSerializer


class ArticleSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()

    class Meta:
        model = Article
        fields = '__all__'
from rest_framework import serializers
from .models import Author

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'

现在,如果我希望从我的API中获取文章,那很简单。获得文章会附上作者的话,这一切都很好-但是我如何得出相反的结论?例如,如果我想让作者获得他们撰写的最新5篇文章?因此预期的输出将类似于:

{
    "first_name": "Sethen",
    "last_name": "Maleno",
    "articles": [
      {
          "text": "some article"
      },
      {
          "text": "another article"
      }
    ]
}

1 个答案:

答案 0 :(得分:2)

class ArticleWithoutAuthorSerializer(ArticleSerializer):
    # Prevent author field serialization and endless nesting
    author = None

class AuthorSerializer(ModelSerializer):
    articles = SerializerMethodField()

    def get_articles(self, author):
        # Five recently posted articles
        articles = author.article_set.order_by('-published')[:5]
        return ArticleWithoutAuthorSerializer(articles, many=True).data

    class Meta:
        model = Author