假设我有查询:
ExampleModel.objects.filter(some_datetime_field__gte=start, some_datetime_field__lte=end)
如何获取上述查询中“开始”和“结束”中出现的所有月份的列表。
例如:
IF
start= 1/10/2018 and end=10/1/2019
然后输出将是:
OCTOBER
NOVEMBER
DECEMBER
JANUARY
有人知道如何执行此操作吗?
提前谢谢
答案 0 :(得分:2)
您可以提取月份,然后获取其名称
from django.db.models.functions import ExtractMonth
months = (
ExampleModel.objects
.filter(some_datetime_field__gte=start, some_datetime_field__lte=end)
.annotate(month=ExtractMonth('some_datetime_field'))
.values_list('month', flat=True)
.distinct()
)
在此代码的结尾,您将获得一个月列表(数字)。例如
[1, 3, 6, 8]
您可以使用calendar
import calendar
[calendar.month_name[month] for month in months]
答案 1 :(得分:0)
您可以使用注释和Query Expressions。
import calendar
from django.db.models import Case, When, Value, CharField
conditions = []
for i in range(1, 13):
month_name = calendar.month_name[i]
conditions.append(When(some_datetime_field__month=i, then=Value(month_name)))
# conditions will be like below
# [
# When(some_datetime_field__month=1, then=Value('January')),
# When(some_datetime_field__month=2, then=Value('February')),
# ...
# ]
ExampleModel.objects.annotate(
month_name=Case(*conditions, default=Value(""), output_field=CharField())
).order_by("month_name").values_list("month_name", flat=True).distinct()
# Result will be like
# <ExampleModelQuerySet ['January', 'September']>