Home > Net >  Django: how to use .filter( ) method in django?
Django: how to use .filter( ) method in django?

Time:07-08

I am trying to display quiz only for users that are registered in a particular course, i.e if a user is registered in a Frontend Crash Course i want them to see only the quiz related to that course they are registered in, and not all the quiz from the db.

i have a model UserCourse where i am storing all the courses a user have enrolled in, when i try filtering by that models while user_course is get like this below

user_course = UserCourse.objects.get(user=request.user)
quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))

i get this error get() returned more than one UserCourse -- it returned 3! Now i have changed .get() to .filter() like this

user_course = UserCourse.objects.filter(user=request.user)
quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))

i then get this error The QuerySet value for an exact lookup must be limited to one result using slicing.

What is the right way to write this query.

models.py

class UserCourse(models.Model):
    user = models.ForeignKey(User , null = False , on_delete=models.CASCADE)
    course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="usercourse")



class Quiz(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quizzes")
    title = models.CharField(max_length=255)
    course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True, related_name="quizzes")
    date = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True)
    user_course = models.ForeignKey(UserCourse, on_delete=models.SET_NULL, null=True)
    def __str__(self):
        return self.title

CodePudding user response:

The Problem in the Second Line

user_course = UserCourse.objects.filter(user=request.user)
quizzes=Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))

remember that when You are using filter you get QuerySet not one object if you want to return the quizes those related to user_course_queryset you can use __in filter

print(user_course) # print it to understand more 
quizzes=Quiz.objects.filter(course__usercourse__in=user_course)

this will Return every Quiz Related to the QuerySet objects

  • Related