[英]How to combine a custom date and time field in Django?
I'm looking for a way to combine a custom date value and a time field in django. 我正在寻找一种在django中结合自定义日期值和时间字段的方法。 My model only contains a time field.
我的模型仅包含一个时间字段。 Now I have to annotate a new field combining a custom date and the time field.
现在,我必须注释一个结合了自定义日期和时间字段的新字段。 I thought the following code will solve my problem, but it only gives the date value.
我以为下面的代码可以解决我的问题,但是只给出了日期值。 TimeField is ignored.
TimeField被忽略。
class MyModel(models.Model):
my_time_field = TimeField()
custom_date = datetime.today().date()
objects = MyModel.objects.annotate(
custom_datetime=Func(
custom_date + F('my_time_field'),
function='DATE'
)
)
Please advise the right way to solve this issue. 请提出解决此问题的正确方法。
You should be able to use a Value
expression (see the docs ) in a manner similar to this: 您应该能够以类似于以下方式使用
Value
表达式(请参阅docs ):
class MyModel(models.Model):
my_time_field = TimeField()
custom_date = datetime.today().date()
MyModel.objects.annotate(
custom_datetime=Value(
datetime.datetime.combine(custom_date, F('my_time_field')),
output_field=DateTimeField()))
The key parts are to combine your custom_date
, the time from your my_time_field
, and then output it as a DateTimeField
. 关键的部分是你的结合
custom_date
,时间从你my_time_field
,然后输出它作为DateTimeField
。
It was an easy solution, but took a while for me to figure it out. 这是一个简单的解决方案,但是我花了一些时间才弄清楚。 If anyone else having the same question, this is the answer.
如果其他人有相同的问题,这就是答案。 Just use
ExpressionWrapper
. 只需使用
ExpressionWrapper
。
objects = MyModel.objects.annotate(
custom_datetime=ExpressionWrapper(
custom_date + F('my_time_field'),
output_field=DateTimeField()
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.