我有两个这样的模型:
class Schedule(models.Model):
name = models.CharField(_('name'), blank=True, max_length=15)
class Day(models.Model):
DAYS_OF_THE_WEEK = (
(0, _('Monday')),
(1, _('Tuesday')),
(2, _('Wednesday')),
(3, _('Thursday')),
(4, _('Friday')),
(5, _('Saturday')),
(6, _('Sunday')),
)
schedule = models.ForeignKey(Schedule, blank=True, null=True, verbose_name=_('schedule'))
day = models.SmallIntegerField(_('day'), choices=DAYS_OF_THE_WEEK)
opening = models.TimeField(_('opening'), blank=True)
closing = models.TimeField(_('closing'), blank=True)
计划可能有两个Day对象,如下所示:
Day(schedule = 1,day = 0,opening = datetime.time(7,30),closing = datetime.time(10,30))
Day(schedule = 1,day = 0,opening = datetime.time(12,30),closing = datetime.time(15,30))
喜欢同一天不同的班次.
如果我现在迭代它们,我会得到第0天的两个条目,就像这样
[日程安排]
[0,0,1,2,3,4,5,6]
如何创建一个查询集,以便它将相同的日期组合在一起并保留其属性?
[day for day in schedule]
[0 (two entries), 1, 3, 4, 5, 6]
也许是这样的
[id: [day], id: [day]]
最佳答案 我最终使用的代码是这样的:
from itertools import groupby
day_set = store.schedule_set.all()[0].day_set.all()
schedule = dict()
for k, v in groupby(day_set, lambda x: x.day):
schedule[k] = list(v)
并将计划发送到模板进行渲染,其效果就像一个魅力.