Reputation: 3680
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")
Upvotes: 4
Views: 12482
Reputation: 46
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
Upvotes: 1
Reputation: 918
#models.py
class Telephone(models.Model):
status = models.IntegerField(default=0)
number = models.CharField(max_length=255, blank=True)
class Profile(models.Model):
first_name = models.CharField(max_length=255, blank=True)
last_name = models.CharField(max_length=255, blank=True)
telephone = models.ManyToManyField(Telephone, blank=True, null=True)
#views.py
def api(request):
profile = Profile.objects.get(pk=1) #just as an example
primary_telephone = profile.telephone.all().filter(status=1)
#I was looking for the primary telephone of my client, this was the way I have solved.
Upvotes: 0
Reputation: 6452
Try:
current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)
Upvotes: 4