Django Rest Framework-如何在ListCreateAPIView

时间:2018-07-12 12:27:51

标签: django post django-rest-framework

发布模型

class Post(models.Model):
    owner = models.ForeignKey(Profile, on_delete=models.CASCADE) # Profile is another model
    title = models.CharField(max_length=300)
    content = models.CharField(max_length=1000)
    votes = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) # Subreddit is another model

PostSerializer

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

ListPostsOfReddit

class ListPostsOfReddit(ListCreateAPIView):
    serializer_class = PostSerializer

    def get_queryset(self):
        return Post.objects.filter(subreddit__name=self.kwargs['r_name'])

其余框架ListCreateAPIView中,我可以获取所有外键数据。在休息框架提供的形式中,仅

  • 标题
  • 内容
  • 投票
要求输入

,我也希望输入外键字段。我该如何实现?

1 个答案:

答案 0 :(得分:2)

使用两个序列化器,并使用get_serializer()方法进行管理。

class PostListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'
        depth = 1


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


class ListPostsOfReddit(ListCreateAPIView):
    def get_serializer_class(self):
        if self.request.method == 'GET':
            return PostListSerializer
        return PostSerializer

    def get_queryset(self):
        return Post.objects.filter(subreddit__name=self.kwargs['r_name'])


注意:我没有测试/验证解决方案。请让我知道是否发生任何错误