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")
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:
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: