Django ORM条件过滤器 [英] Django ORM conditional filter LIKE CASE WHEN THEN
问题描述
我正在使用Django 1.11,Postgresql 9.2,python 3.4
I'm using Django 1.11, Postgresql 9.2, python 3.4
如果事件类型为单个,我想基于名为event_type
的表的列选择数据,然后比较应该为同一日期(今天)的日期,否则选择给定的所有日期(今天)该类型为重复发生的日期.
I want to select data based on table's column named event_type
if event type is single then compare date that should be of same date (today's) date else select all dates of given (today's) date that type would be of recurring.
但是我们不能使用单个查询来管理它吗?就像我们在汇总中执行CASE
和WHEN
,THEN
一样吗?我尝试使用Q
对象,但没有运气.
我想检查值何时为单个",然后添加条件,否则为另一个条件.
But can't we manage this using single query? Like we do CASE
and WHEN
, THEN
in Aggregation? I tried using Q
object but no luck.
I want to check when value is 'single' then add condition, else another condition.
I could not find any good solution, currently I've achieved using this
today = datetime.date.today().strftime('%Y-%m-%d')
single_events = crm_models.EventsMeta.objects.filter(
event_type == "single",
repeat_start=today
)
recurring_events = crm_models.EventsMeta.objects.filter(
event_type == "recurring"
repeat_start__lte=today
)
all_events = single_events | recurring_events
有关更多信息,我的模型是:
For more information my model is:
class EventsMeta(models.Model):
event_type = models.CharField(max_length=50, choices=(("single","Single"),("recurring","Recurring")),
null=False, blank=False,default='single',verbose_name="Event Type")
repeat_start = models.DateTimeField()
repeat_end = models.DateTimeField()
推荐答案
您可以将许多带有()
符号的Q对象组合在一起.如果您的情况适合我,我想这是可行的:
You can combine many Q objects with ()
signs. I your case I suppose this will work:
single_events = crm_models.EventsMeta.objects.filter(
(Q(event_type="single") & Q(repeat_start=today)) |
(Q(event_type="recurring") & Q(repeat_start__lte=today))
)
这篇关于Django ORM条件过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!