如何在Django休息框架中使用一对多模型

时间:2016-01-10 16:12:17

标签: django rest django-rest-framework

我有两个简单的模型,第一个是

class Post(models.Model):
    user = models.ForeignKey("common.MyUser", related_name="post_user")
    act = models.ForeignKey("activities.Act", related_name="post_act")
    post_title = models.CharField(max_length=30, blank=True)
    post_content = models.CharField(max_length=140)
    post_thumb_url = models.URLField()
    post_create_time = models.DateTimeField(auto_now=True)

,第二个是

class Comment(models.Model):
    post = models.ForeignKey("post.Post", related_name="comment_post")
    user = models.ForeignKey("common.MyUser", related_name="comment_user")
    reply_id = models.IntegerField()
    comment_content = models.CharField(max_length=140)
    comment_create_time = models.DateTimeField(auto_now=True)

每篇文章都可能有一些评论。现在我想使用帖子ID获取每个帖子信息以及所有评论。例如:

api.example.com/post/?post_id=1 (此帖有两条评论) 并返回

 {
        "id": 26,
        "user": 22,
        "post_comment": [{
            "reply_id": 12,
            "comment_content": "How are you doing",
            "comment_create_time": "2015-11-19",
        },
        {
             "reply_id": 32,
            "comment_content": "My name is Sun",
            "comment_create_time": "2015-11-19",
        }]
        "post_title": " ",
        "post_content": "Thank you,bro.",
        "post_thumb_url": "http://www.example.com",
        "post_create_time": "2013-12-31"
}

在Django休息框架中,我使用了这个

class PostSerializer(serializers.ModelSerializer):
"""Post api fields"""
post_comment = CommentSerializer(source="comment_post") //this may be the key

class Meta:
    model = Post
    fields = ("id", "user","post_comment", "post_title", "post_content", "post_thumb_url", "post_create_time") 

class CommentSerializer(serializers.ModelSerializer):
    """Comment api fields"""

class Meta:
    model = Comment
    fields = ("id", "reply_id","comment_content", "comment_create_time", "post", "user")

任何使这项工作的方法?感谢。

编辑:这是我的观点

class PostList(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly)
    queryset = Post.objects.all()
    serializer_class = CommentSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def get_queryset(self):
        queryset = Post.objects.all()
        post_id = self.request.query_params.get('post_id', None)
        if post_id is not None:
            queryset = queryset.filter(id=post_id)
        return queryset

1 个答案:

答案 0 :(得分:2)

您应该设置many=True参数。

# ##################
# ##### MODELS #####
# ##################

class Post(models.Model):
    user = models.ForeignKey("common.MyUser", related_name="post_user")
    act = models.ForeignKey("activities.Act", related_name="post_act")
    post_title = models.CharField(max_length=30, blank=True)
    post_content = models.CharField(max_length=140)
    post_thumb_url = models.URLField()
    post_create_time = models.DateTimeField(auto_now=True)

class Comment(models.Model):
    post = models.ForeignKey("post.Post", related_name="comment_post")
    user = models.ForeignKey("common.MyUser", related_name="comment_user")
    reply_id = models.IntegerField()
    comment_content = models.CharField(max_length=140)
    comment_create_time = models.DateTimeField(auto_now=True)


# #######################
# ##### SERIALIZERS #####
# #######################

class CommentSerializer(serializers.ModelSerializer):
  class Meta:
    model = Comment
    fields = ("id", "reply_id","comment_content", "comment_create_time", "post", "user")

class PostSerializer(serializers.ModelSerializer):
    # This line is what changed:
    # post_comment = CommentSerializer(source="comment_post")
    post_comment = CommentSerializer(many=True)

    class Meta:
        model = Post
        fields = ("id", "user","post_comment", "post_title", "post_content", "post_thumb_url", "post_create_time")