Django、日付範囲内の指定された月と年でフィルタリングする 質問する

Django、日付範囲内の指定された月と年でフィルタリングする 質問する

以下のモデルを所有しています

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 の間にある場合に、Destination_Deals をフィルターしたいと思います。

例1

月: 9月 (09)
年: 2012

希望出発日の結果:
ID 3 : 2012年9月に触れる唯一のデータ範囲です

例2

月: 2月 (02)
年: 2013

希望出発日の結果:
ID 1: 2012/02 は 2012/03 より前です

したがって、実際の日付は関係ありません。月と年が date_from と date_to の間にある場合は、1 日であってもフィルターする必要があります。

私は次のようなものを使う必要があると思うこれしかし、どうすればいいのか分かりません。

- -編集 - -
これは、Aamir Adnan からの回答のテストですが、2012 年 11 月から 2013 年 3 月までなので 2013 年 1 月が間にあり、ID 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>]

ベストアンサー1

チェックしてくださいドキュメンテーション

year = 2012
month = 09
Departure_Date.objects.filter(date_from__year__gte=year,
                              date_from__month__gte=month,
                              date_to__year__lte=year,
                              date_to__month__lte=month)

代替方法.extra:

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])

上記のクエリで目的の結果が得られない特定のケースがあります。

例えば:

date_from='2012-11-01'
date_to='2013-03-17'
and input is
year=2013
month=1

この場合、%(month)s >= MONTH(date_from)月 1 は月 11 より小さいですdate_fromが、年が異なるため条件が間違っています。そのため、IFここでは MySQL 条件が必要です。

where = '%(year)s >= YEAR(date_from) AND IF(%(year)s > YEAR(date_from), \
     IF(%(month)s > MONTH(date_from), %(month)s >= MONTH(date_from), %(month)s < MONTH(date_from)), \
     IF(%(month)s < MONTH(date_from), %(month)s < MONTH(date_from), %(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])

おすすめ記事