我有以下型号
class Destination_Deal(models.Model):
name = models.CharField(_("Nombre"),max_length=200)
class Departure_Date(models.Model):
date_from= models.DateField(_('Desde'))
date_to= models.DateField(_('Hasta'))
destination_deal = models.ForeignKey(Destination_Deal,verbose_name = _("Oferta de Destino"))
这是表中的实际数据
id date_from date_to destination_deal_id
1 2012-11-01 2013-03-17 1
2 2012-11-01 2012-12-16 2
3 2012-09-16 2012-10-31 3
4 2012-11-01 2012-12-16 3
5 2013-01-04 2013-01-11 4
如果指定的月份和年份在 date_from 和 date_to 之间,我想过滤 Destination_Deals。
示例 1
月份:9 月 (09)
年份:2012
想要的出发日期结果:
ID 3:它是唯一触及 09/2012 的数据范围
示例 2
月份:2 月 (02)
年份:2013
想要的出发日期结果:
ID 1:02/2012 在 03/2012 之前
所以,日子其实是无所谓的。如果月份和年份在 date_from 和 date_to 之间,即使相差一天也必须过滤。
我想我必须使用这样的东西,但我不知道该怎么做。
提前致谢!米格尔
---编辑---
这是对 Aamir Adnan 答案的测试,但它没有像我预期的那样工作,因为 ID 1 也必须返回,因为它从 2012 年 11 月到 2013 年 3 月,所以 2013 年 1 月介于两者之间。
Departure_Date.objects.all()
[<Departure_Date: id: 1 - from: 2012-11-01 - to: 2013-03-17>,
<Departure_Date: id: 2 - from: 2012-11-01 - to: 2012-12-16>,
<Departure_Date: id: 3 - from: 2012-09-16 - to: 2012-10-31>,
<Departure_Date: id: 4 - from: 2012-11-01 - to: 2012-12-16>,
<Departure_Date: id: 5 - from: 2013-01-04 - to: 2013-01-11>]
month:1
year:2013
where = '%(year)s >= YEAR(date_from) AND %(month)s >= MONTH(date_from) \
AND %(year)s <= YEAR(date_to) AND %(month)s <= MONTH(date_to)' % \
{'year': year, 'month': month}
Departure_Date.objects.extra(where=[where])
[<Departure_Date: id: 5 - from: 2013-01-04 - to: 2013-01-11>]