Django会获得父母名单,每个父母都有自己的孩子

时间:2019-05-23 04:25:29

标签: python django django-rest-framework

我有一对父母/孩子关系模型,例如:

class Post(models.Model):
    title = models.TextField(null=True)
    content = models.TextField(null=True)
    author = models.TextField(null=True)
    created_time = models.DateTimeField(null=True)


class Comment(models.Model):
    content = models.TextField(null=True)
    created_time = models.DateTimeField(null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

和序列化器类似:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'

最后是视图:

class PostView(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer


class CommentView(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

现在,我想创建一个API,该API返回一个Post列表,其中每个Post将包含两个附加字段,一个为all_comments,另一个为{ {1}}。我知道可以使用latest_comment在SQL中轻松完成此操作。我是Django的新手。我想知道在Django中是否有任何简便的方法。谢谢。

1 个答案:

答案 0 :(得分:4)

希望此配置对您有用:)

class CommentPostSerializer(serializers.ModelSerializer): # New Serializer class
    class Meta:
        model = Comment
        exclude = ('post',)


class PostSerializer(serializers.ModelSerializer):
    all_comments = CommentPostSerializer(read_only=True, many=True, source='comment_set')
    latest_comment = serializers.SerializerMethodField()

    def get_latest_comment(self, post):
        latest_comment = post.comment_set.last()
        return CommentPostSerializer(latest_comment).data

    class Meta:
        model = Post
        fields = '__all__'