Django,queryset过滤ManyToManyField

时间:2014-04-26 16:54:09

标签: python django filter django-orm

我确实有以下两种型号。所以我试图获得特定课程的所有模块。正如你所看到的,我已经得到了那个特定的课程。所以我只需要从中获取模块。我阅读the docs有关过滤ManyToManyField但仍无法使其正常工作的信息。我知道也许它太简单但无法解决它。

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 个答案:

答案 0 :(得分:4)

尝试:

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

答案 1 :(得分:0)

#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.

答案 2 :(得分:0)

您在课程模型上有一个相关字段,它是M2M到模块,因此您可以访问与课程直接相关的模块列表。

完成课程后,只需获取所有模块:

course = Course.objects.get(pk=course_id)
course_modules = course.modules.all()

我总是建议用try / except来包装查询Course的第一行 - 这是因为如果找不到结果,模型管理器的get方法会抛出异常。

这可以这样做:

try:
    course = Course.objects.get(pk=course_id)
except Course.DoesNotExist:
    pass  # Handle this exception