如何检索用户使用djangorest框架创建的所有项目

lnlaulya  于 2022-12-24  发布在  Go
关注(0)|答案(3)|浏览(121)

我试图只获取属于下面某个特定用户的课程我有模型,序列化器和视图来尝试和实现这一点。如果我从视图中删除整个get_queryset函数,api将返回相应的用户和每个用户创建的每个课程。如果get_queryset仍然存在,api总是返回找不到的用户,并且仍然给出存在的每一门课程。有没有人能告诉我如何才能达到我想要的结果。
查看:

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsProfileOwnerOrReadOnly]
    # queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = User.objects.all()
        if user is not None:
            queryset = queryset.filter(courses__owner_id=user.id)
        return queryset

串化器

class UserSerializer(serializers.ModelSerializer):
    courses = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Course.objects.all())
    class Meta:
        model = User
        fields = ['id', 'username', 'courses']

型号

class Course (models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    pub_date = models.DateField(default=date.today)
    owner = models.ForeignKey('auth.User', related_name='courses', on_delete=models.CASCADE)
    def __str__(self):
        return self.title
qgzx9mmu

qgzx9mmu1#

您需要按用户筛选对象

class CreatePostsView(viewsets.ModelViewSet):
        model = Post
        serializer_class = PostsSerializer

        def get_queryset(self):
            user = self.request.user

            return Post.objects.filter(owner=user)
f87krz0w

f87krz0w2#

class CoursesByOwnerView(RetrieveModelMixin, GenericViewSet):
        serializer_class = YourModelSerializer
        authentication_classes =[TokenAuthentication,]
        permission_classes = [IsAuthenticated,]
    

        def list(self, request, *args, **kwargs):
           course_taker = self.request.user
           courses = YourModel.objects.filter(owner=course_taker).values('your_model_fields')
           return Response(courses)
pokxtpni

pokxtpni3#

鉴于您在评论中的回答:

  • 或者使用认证中间件提供的self.request.user,这种情况下只对认证用户有效,其他用户的课程看不到。
  • 您可以使用您提到的端点users/<int:pk>/。在这种情况下,您可以使用以下命令获取用户:
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsProfileOwnerOrReadOnly]
    serializer_class = UserSerializer

    def get_queryset(self):
        return UserDetail.objects.filter(pk=self.kwargs["pk"])

如果您需要另一个示例,请参阅此主题:Django 2.0 url parameters in get_queryset
EDIT:在这两种情况下,请使用以下命令更改UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    courses = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True)
    class Meta:
        model = User
        fields = ['id', 'username', 'courses']

相关问题