Group objects with the same field value

I have two models:

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 is possible that the schedule may have two Day objects, for example:

Day (schedule = 1, day = 0, opening = datetime.time (7, 30), closing = datetime.time (10, 30)) Day (schedule = 1, day = 0, opening = time datetime.time (12 , 30), closing = datetime.time (15, 30))

like different shifts that day.

If I repeat them now, I will get two entries of day 0, for example [day after day in the schedule] [0, 0, 1, 2, 3, 4, 5, 6]

How can I create a set of queries so that it groups the same days together and stores their attributes?

[day for day in schedule]
[0 (two entries), 1, 3, 4, 5, 6]

Maybe something like

[id: [day], id: [day]]
+3
source share
2 answers

The code I used is as follows:

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)

, .

+5

, {% regroup%} {% for %} -loop {% ifchanged%}.

Python groupby.

+2

All Articles