Django,查询集过滤器ManyToManyField [英] Django, queryset filter ManyToManyField

查看:341
本文介绍了Django,查询集过滤器ManyToManyField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有以下两种型号。因此,我正在尝试获取特定课程的所有模块。如您所见,我已经修完了这门课程。因此,我只需要从中获取模块。我阅读了文档有关过滤ManyToManyField的内容,但仍然无法做到使其起作用。我知道这也许太简单了,但解决不了。

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

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


推荐答案

尝试:

current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)

这篇关于Django,查询集过滤器ManyToManyField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆