简体   繁体   中英

Django filter with 'day-month' together without consider year

I want to filter my datetime field with 1 month after from today without consider year.

class Contract(models.Model):
    title = models.CharField(max_length=200, null=True)
    date = models.DateField()

Example filter between: From: Today Day and Month: 01-05 (%m-%d) To: One Month Later: 02-05 (%m-%d)

Here is my code:

        today = datetime.date.today()
        foremonth = today + relativedelta(months=1)
        return_list=[]
        s = Contract.objects.filter(active=True).order_by('date__month', 'date__day')
        for i in s:
            k = i.date.strftime("%m-%d")
            if k > today.strftime("%m-%d") and k < foremonth.strftime("%m-%d"):
                return_list.append(i)
        return return_list

How can I do with django query

What you could do is use the Django database functions as described here , Django annotations and combine them with Q to create the query.

  1. You results need to fullfill the conditions that either the day is greater than your starting day AND the month is our starting month OR the day is smaller than your end day AND the month is your end month. So we need the day and month values for these conditions.
  2. Then we create the query conditions using Q as we need an OR.
  3. Finally we annotate the Contract objects with day and month values and apply the filter.
    today = datetime.date.today()
    foremonth = today + relativedelta(months=1)

    start_day = today.day
    start_month = today.month
    end_day = foremonth.day
    end_month = foremonth.month

    # Create the query
    query = Q(d__gte=start_day, m=start_month) | Q(d__lte=end_day, m=end_month)

    # Annotate your objects with day and month and filter results

    Contract.objects.annotate(d=ExtractDay('date'), m=ExtractMonth('date')).filter(query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM