In the College
model, I have a field named courses_info
which contains multiple entries. There are a total of 114 courses available. Each college offers different courses. For example, let’s consider that College1 offers 10 courses, including BSc, MSc, and 8 other courses. Please write a Django ORM query to filter these courses.
Show your models.py, your view.py and your templates.
Most probably something like that would work:
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=200)
class College(models.Model):
name = models.CharField(max_length=200)
courses = models.ManyToManyField(Course, related_name='colleges')
Now, let’s say you want to get all the courses offered by a specific college. You can do this with the following query:
college = College.objects.get(name='College1')
courses = college.courses.all()
This will return a QuerySet of Course objects that are related to the College object with the name ‘College1’.
If you want to filter the courses based on some criteria, you can chain additional filter conditions. For example, to get only the courses with names ‘BSc’ or ‘MSc’, you can do:
courses = college.courses.filter(name__in=['BSc', 'MSc'])