I’ve got two models like these:
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)
It’s possible that a schedule can have two Day objects like so:
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))
like different shifts on the same day.
If I iterate them now i’ll get two entries of day 0, like so
[day for day in schedule]
[0, 0, 1, 2, 3, 4, 5, 6]
How can I create a queryset so it’ll group same days together and keep their attributes?
[day for day in schedule]
[0 (two entries), 1, 3, 4, 5, 6]
Maybe something like
[id: [day], id: [day]]
The code I ended up using is this:
and sending schedule to the template for rendering, which works like a charm.