Django, filter by specified month and year in date range

后端 未结 3 2015
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 01:04

I have the following models

class Destination_Deal(models.Model):
    name = models.CharField(_(\"Nombre\"),max_length=200)

class Departure_Date(models.Model):         


        
3条回答
  •  無奈伤痛
    2021-02-05 01:17

    Solution using python code only. Main idea is to construct date_from and date_to with python. Then these dates can be used in filter with __lte and __gte:

    import calendar
    from datetime import datetime
    from django.db.models import Q
    
    def in_month_year(month, year):
        d_fmt = "{0:>02}.{1:>02}.{2}"
        date_from = datetime.strptime(
            d_fmt.format(1, month, year), '%d.%m.%Y').date()
        last_day_of_month = calendar.monthrange(year, month)[1]
        date_to = datetime.strptime(
            d_fmt.format(last_day_of_month, month, year), '%d.%m.%Y').date()
        return Departure_Date.objects.filter(
            Q(date_from__gte=date_from, date_from__lte=date_to)
             |
            Q(date_from__lt=date_from, date_to__gte=date_from))
    

    Now this will work:

    >>> Departure_Date.objects.all()
    [,
    ,
    ,
    ,
    ]
    
    
    >>> in_month_year(month=1, year=2013)
    [,
    ]
    

提交回复
热议问题