0

我有以下课程模型,我想找到每节课之前或之后(少于 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 吗?如果是,我怎样才能找到这些课程?

4

1 回答 1

0

是的,您可以使用Q它来创建查询,AND并且OR

考虑到您手头有课程数据,

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

当然,您可以使用单条语句作为连接两个查询。你也可以&像这样使用

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(....))

这是复杂查找参数的文档...

于 2012-06-16T15:27:47.043 回答