【发布时间】:2019-02-04 15:53:17
【问题描述】:
所以我一直在尝试做的是让我的 API 视图仅将具有 post_user 属性的对象返回到登录用户的当前 ID。这些post_user 属性被填充,因为每当我发布它时,它都会通过我的序列化程序使用当前用户的ID 填充变量。
但是,我没有成功,因为它说请求未定义。我只想获取当前用户的 id,以便我可以使用它来过滤我的对象返回
views.py
# To retrieve and list all posts with DRF
class ListPosts(generics.ListCreateAPIView):
queryset = Posts.objects.get(post_user=request.user.id)
serializer_class = PostsSerializer
permission_classes = (permissions.IsAuthenticated,)
序列化器.py
# serializer for posts to be taken
class PostsSerializer(serializers.ModelSerializer):
class Meta:
model = Posts
fields = ('id','post_title','post_content',)
def create(self, validated_data):
posts = Posts.objects.create(
post_title=validated_data['post_title'],
post_content=validated_data['post_content'],
# gets the id of the current user
post_user=self.context['request'].user.id,
)
posts.save()
return posts
【问题讨论】:
标签: python-3.x django-rest-framework