django query:如何使用模型查询API查找具有相同参数的课程

时间:2012-06-15 17:42:32

标签: django django-queryset

我有以下课程模型,我想通过相同的语言,房间和老师的课程找到之前或之后(不到15分钟)的每一课;

class Lesson(models.Model):
      room = models.ForeignKey(Room, null=True, blank = True)
      language = models.ForeignKey(Lnaguage)
      teacher = models.ForeignKey(Teacher, null=True, blank = True)
      start = models.TimeField()
      end = models.TimeField()
      date = models.DateField()

这是否可以使用django的模型查询API?如果是,我怎样才能找到这些课程?

1 个答案:

答案 0 :(得分:0)

是的,您可以使用QANDOR

创建查询

考虑您手头有课程数据,

lesson = Lesson.objects.get(id=......)

大于

from django.db.models. import Q
from datetime import timedelta

filtered_lessons = Lesson.objects.filter( (Q(start__lt=lesson.end+timedelta(minutes=15)) | Q(end__gt=lesson.start-timedelta(minutes=15)))) # define time criteria using OR

filtered_lessons.filter(date=lesson.date, room=lesson.room, teacher=lesson.teacher, language=lesson.language) #apply the other filters

当然,您可以使用sfingle语句加入两个查询。您也可以使用&之类的

filtered_lessons = Lesson.objects.filter( Q(Q(start__lt=lesson.end+timedelta(minutes=15)) | Q(end__gt=lesson.start-timedelta(minutes=15))) & Q(teaher=lesson.teacher) &Q(....) & Q(....))

Here is the documentation用于复杂的查找参数...