使用此模型
class Event(models.Model):
name = models.CharField('Name', max_length = 200)
class EventSchedule(models.Model):
event = models.ForeignKey(Event)
active = models.BooleanField(default = False)
sales_start = models.DateTimeField('Sales start')
sales_finish = models.DateTimeField('Sales end')
如何有效地获取至少有一个活动的EventSchedule且在销售开始和结束时段内的所有Events对象?
EventSchedule对象的过滤器是
filter(active = True, sales_start__lte = now, sales_finish__gte = now)
但是我需要Event对象而不是EventSchedule对象吗?
答案 0 :(得分:3)
使用双下划线语法遍历关系:
Event.objects.filter(eventschedule__active=True,
eventschedule__sales_start__lte=now,
eventschedule__sales_finish__gte=now)
已修改实际上,上述代码将显示具有符合任何这些条件的日程安排的事件,即使它们不是相同的日程安排。这实际上需要一个子查询,可以这样做:
Event.objects.filter(eventschedule__in=EventSchedule.objects.filter(
(active=True, sales_start__lte=now, sales_finish__gte=now))
第三次尝试这样更好吗?
Event.objects.filter(id__in=EventSchedule.objects.values_list('event').filter(
(active=True, sales_start__lte=now, sales_finish__gte=now)).distinct()
答案 1 :(得分:0)
我只想简单:
events = []
obj = EventSchedule.objects.filter(active=True, sales_start__lte=now, sales_finish__gte=now)
for i in obj:
if not i.event in events:
events.append(i.event)