可能在Django queryset中的两个日期之间获得几个月的时间? [英] its possible to get months between two dates in django queryset?
本文介绍了可能在Django queryset中的两个日期之间获得几个月的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试建立一个完整的查询集,现在我需要从模型中获取两个 DateTime
字段之间的月份,可以在单个查询集中执行此操作.我不是在说过滤器,例如在模型中,因为我有两个 datetimeField()
,现在我要做的是在两个日期之间间隔几个月.
I'm trying to get make a complete query set, and now all I need is get the months between two DateTime
fields from my model, it's possible to do this action in a single query set.
Im not talking about filter, cause in the model for example I have two datetimeField()
and now what I want to do is, gets months between this dates.
推荐答案
如果您的数据库支持 DurationField
,则可以使用
If your database supports DurationField
you can go with ExtractMonth:
from django.db import models
from django.db.models.functions import ExtractMonth
queryset = MyModel.objects.annotate(
diff=models.ExpressionWrapper(
models.F('date1') - models.F('date2'), output_field=models.DurationField())
).annotate(months=ExtractMonth('diff'))
这篇关于可能在Django queryset中的两个日期之间获得几个月的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文