过滤合并日期和时间在django [英] filter combined date and time in django

查看:167
本文介绍了过滤合并日期和时间在django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型分开的日期和时间,我想过滤未来的事件,最后写这个,这不是很酷。有更好的方法吗?我可以以某种方式使用combine()和min()吗?正如您在查询中可以看到的那样,它必须包括今天的事件与时间>现在

  future_events = CauseEvent.objects.filter ()=(())()=() .exists()


解决方案

使用 Q对象

 $ d code从django.db.models导入Q 

today = datetime.now()。date()
now = datetime.now()。time()

future_events = CauseEvent.objects.filter(cause = instance)\
.exclude(Q(date__lt = today)|
Q(date = today,time__lt = now)


I have a model with separated date and time, I want to filter for future events and ended up writing this, which is not cool. Is there a more nicer way? Can I use combine() and min() in some way for this? As you can see in the query, it must include the today events with time > now

future_events = CauseEvent.objects.filter(cause=instance).exclude(date__lt=datetime.now().date()).exclude(date=datetime.now().date(),
                                                                                                                  time__lt=datetime.now().time()).exists()

解决方案

Lookup using Q objects:

from django.db.models import Q

today = datetime.now().date()
now = datetime.now().time()

future_events = CauseEvent.objects.filter(cause=instance) \
                                  .exclude(Q(date__lt=today) |
                                           Q(date=today, time__lt=now))

这篇关于过滤合并日期和时间在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆