django - 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()
...
...
解决方案
您实际上可以通过直接注释查询集来按月和年分组,如下所示:
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
推荐阅读
- angular - 如何将信息从ngrx提取到组件文件
- java - 如何编写正则表达式来查找日期和时间
- html - 单击按钮时,我的输出重复一次
- java - 可选在 orElse 之前进行额外处理
- scala - Spark 从整个 Schema Scala 中读取
- database - 有没有办法在颤动中划分来自 API 的数据?
- laravel - laravel 的条纹 webhook
- html - PrimeNG p-table 只显示表的名称
- powershell - 我想创建一个文件,它将获取 1.csv 的标题并从 2.csv 中提取所有数据。在 Powershell 中
- visual-c++ - 如何调用 LimitText 而不会导致派生 CComboBox 异常