日期范围头痛

时间:2009-09-07 13:52:16

标签: django django-models

#model
class Promotion(models.Model):
    name = models.CharField(max_length=200)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()


#view
def promo_search(request):
    ...
    results = Promotion.objects.filter(start_date__gte=start_date).filter(end_date__lte=end_date)
    ...

(上面的代码显然不起作用我只是用它来 帮助说明我的问题。)

我想在开始日期和结束之间显示所有有效的促销活动 日期。

因此,如果促销活动于2009年1月1日开始,并于2009年1月30日结束,则为一个人 搜索从08年12月1日到1月2日,它仍将返回结果。也 如果他们从日期范围内搜索,例如02/01/09 - 03/01/09 他们会得到相同的结果。

是否有一些神奇的django方法可以在没有循环的情况下实现这一目标 每天?

1 个答案:

答案 0 :(得分:1)

您需要考虑四个日期:start_searchend_searchstart_promoend_promo。您正在寻找start_promo <= end_searchend_promo >= start_search

的促销活动
results = Promotion.objects.\
            filter(start_date__lte=end_date).\
            filter(end_date__gte=start_date)