0

让我们假设我有两个模型。第一个模型包含诅咒详细信息和创建此课程的用户

class Course(models.Model):
    course_name = models.CharField(max_length=100, null=False)
    description = models.CharField(max_length=255)
    user_profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

我的第二个模型是:

class Lesson(models.Model):
    course = models.OneToOneField(Course, on_delete=models.CASCADE) # 
    # inside the course I want my APIVIEW to list only the courses that current user created. 
    # OnetoOne relationship does not solve the problem. 

    status = models.CharField(choices=STATUS, null=False, default=GOZLEMEDE,max_length=20)
    tariffs = models.FloatField(max_length=5,null=False,default=0.00)
    continues_off = models.CharField(max_length=2)
    user_profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

我的两个模型的序列化器:

class LessonSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Lesson
        fields = ('course', 'status', 'tariffs', 'continues_off', 'user_profile')

        def create(self, validated_data):

            lesson = models.Lesson.objects.create(
                course = validated_data['course'],
                status = validated_data['status'],
                tariffs=validated_data['tariffs'],
                continues_off=validated_data['continues_off'],
                user_profile=validated_data['user_profile']
            )
            return lesson

class CourseSerializer(serializers.ModelSerializer):
    """Serializers Course content"""
    class Meta:
        model = models.Course
        fields = '__all__'

    def create(self,validated_data):
        course = models.Course.objects.create(
            course_name = validated_data['course_name'],
            description=validated_data['description'],
            user_profile=validated_data['user_profile']
        )

        return course

我的视图集:

class LessonViewset(viewsets.ModelViewSet):

    model = models.Lesson
    serializer_class = serializers.LessonSerializer
    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,BasePermission,)

    def get_queryset(self):
        user_current = self.request.user.id
        return models.Lesson.objects.filter(user_profile=user_current)

我怎样才能得到想要的结果。我想获取当前用户的课程并将它们显示为我的 API 视图中的下拉列表。只有用户创建的课程应该在下拉列表中,而不是全部。OnetoOne 关系给出了课程表的所有结果。

4

1 回答 1

0

我认为将您的视图代码更改为:

    def get_queryset(self,id):
        return model.objects.filter(user_profile=id)
#You do not need to call it again when you put the Lesson on the model

\

于 2021-12-08T22:17:45.037 回答