Django, queryset filter ManyToManyField

2019-05-08 15:13发布

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

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-08 15:35

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
查看更多
家丑人穷心不美
3楼-- · 2019-05-08 15:44
#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.
查看更多
成全新的幸福
4楼-- · 2019-05-08 15:45

Try:

current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)
查看更多
登录 后发表回答