Home > Back-end >  Listview must return only the courses that student have puchased in django
Listview must return only the courses that student have puchased in django

Time:09-09

My models

User

class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    ....
    purchased = models.ManyToManyField(Course, blank=True)

Course

class Course(models.Model):
    title = models.CharField(max_length=1000)
    .....
    price = models.FloatField()

My Views

class StudentPurchasedcourse(ListView):
    model = Course
    template_name = 'tutspack/purchasedcourse.html'
    context_object_name =  'course'
    
    def get_queryset(self):
        queruset = Course.objects.filter(pk=self.request.user.purchased.all()).order_by('title')
        return queruset

My Urls.py

path('purchased_course/', views.StudentPurchasedcourse.as_view(), name='purchased-course'),

I want to return all the courses That student have purchased on the studentViewpage. It would be helpful If anyone knows the answer.

CodePudding user response:

You should use reverse relation for such query. Start with adding related_name to purchased field of User:

class User(AbstractUser):
    ...
    purchased = models.ManyToManyField(Course, blank=True, related_name="buyers")

Then you can easily use that name in making queries based on relations:

Course.objects.filter(buyers=self.request.user).order_by('title')

More about queries

  • Related