How to retrieve data from model that current user created and list it for another model's field in django

Let us imagine that I have two models. First model contains curse details and user that created this course

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)

and my second model is:

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)

My serializers for both Models:

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

My Viewset:

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)

How can I get the desired result. I want to get the courses for the current user and show them as a dropdown list in my API view.

i think change your view code to :

    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

\

Back to Top