如何使用向现有日期添加天数在 Django 中进行过滤

How to filter in django using adding days to existing dates

class Payment(models.Model):
    name = models.CharField()
    payment_date = models.DateField()

例子

Table 付款

id   name  payment_date
1    A     2022-01-01
2    B     2022-01-02
3    C     2022-01-02
4    D     2022-01-06

假设每笔付款的到期日为 payment_date+10 天。假设我在日期“2022-01-12”检查到期的记录是

2022-01-01 + 10 days = 2022-01-11 Due
2022-01-02 + 10 days = 2022-01-12 Due
2022-01-06 + 10 days = 2022-01-16 Not Due

所以我的示例输出应该是

Sample:
<QuerySet [<Payment: A>, <Payment: B>, <Payment: C>]>

你可以使用timedelta

from datetime import timedelta

您现在可以像这样向日期时间对象添加天数,然后根据该日期进行过滤

new_date = payment_date+timedelta(days=10)
    

你可以这样做:

from datetime import timedelta
from django.utils import timezone

Payment.objects.filter(
    payment_date__lte=timezone.now() - datetime.timedelta(days=10)
)