Django, queryset filter ManyToManyField
Solution 1
Try:
current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)
Solution 2
You have a related field on the Course model which is a M2M to Module and so this allows you to access the list of modules directly associated to a course.
Once you have the course simply fetch all of it's modules like so:
course = Course.objects.get(pk=course_id)
course_modules = course.modules.all()
I would always advise wrapping the first line that queries Course with a try/except - this is because the model manager's get method can throw an exception if a result cannot be found.
This can be done like so:
try:
course = Course.objects.get(pk=course_id)
except Course.DoesNotExist:
pass # Handle this exception
manosim
Updated on June 25, 2022Comments
-
manosim almost 2 years
I do have the two models below. So I'm trying to get all the modules of a particular course. As you can see, I'm already getting that particular course. So I just need to get the modules from it. I read the docs about filtering a ManyToManyField but still couldn't make it work. I know that maybe it's too simple but can't solve it.
models.py
class Course(models.Model): name = models.CharField(max_length=100) modules = models.ManyToManyField('Module', blank=True) class Module(models.Model): code = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=65) year = models.IntegerField()
view.py
def ajax_get_modules(request, course): current_course = Course.objects.get(pk=course).pk modules = Module.objects.filter(...........) if request.is_ajax(): data = serializers.serialize('json', modules) return HttpResponse(data, content_type="application/javascript")