Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Listview must return only the courses that student have puchased in django

My models

User

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

Course

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading