首页 > 解决方案 > Python按月将列表拆分为各种列表

问题描述

我有一个包含日期属性的对象列表(django 模型)。日/月/年,我需要按月和年将其分成几组,所以如果我有:

list_dates = ['1-10-2018','4-10-2018','1-11-2018',
            '6-10-2018', '3-10-2018', '6-11-2018', '9-11-2018']

实际上是:

list_objects = [a,b,c,d,e,f,g...z]

编辑:每个对象(模型)都有一个date = models.Datetime(),我需要选择和分组具有相同月份和年份的对象。

把它变成

splitted_list = {[a,b,e],[c,d,e]}# same month, same year grouped together

list_grouped = {['1-10-2018','4-10-2018','1-10-2018','6-10-2018'],

['3-11-2018', '6-11-2018', '9-11-2018']}

而且我还没有找到一种简单或可行的方法来做到这一点希望有人知道如何做到这一点。这几天一直在尝试。

'class my_model<(models.Model):
    owner = models.ForeignKey('User', on_delete=models.CASCADE, related_name="model_prods")
    ...  
    ...

class list_v2(models.Model):
    list_owner= models.ForeignKey(my_model, related_name='date_list', on_delete=models.CASCADE)
    date = models.DateField()
    ...
    ...

标签: djangopython-3.xdjango-models

解决方案


您实际上可以通过直接注释查询集来按月和年分组,如下所示:

filtered_queryset = queryset.annotate(month=TruncMonth('date'), year=TruncYear('date'))
filtered_queryset.values_list('month', 'year')

https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#datefield-truncation


推荐阅读