我有以下模型
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"))
这是表格 departure_date 中的实际数据
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之间。
示例1
月份:九月(09)
年份:2012
所需出发日期结果:
ID 3:它是唯一一个接触到09/2012的数据范围。
示例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>]