3

我有一个按钮,应该在模型对象的 start_date 前 1 天出现。在我看来,我有一个函数可以告诉我对象的 start_date 或 end_date 是现在。

    def has_engagement(self):
        from rental.models import Inquiry
        inquiries = Inquiry.objects.filter(inquiryequipment__equipment=self).filter(start_date__lte= timezone.now()).\
            filter(end_date__gte=timezone.now()).filter(status="CO")
        if not inquiries:
            return False
            # no current confirmed engagement
        else:
            return True
            # there is a current confirmed engagement

而不是这个,我需要检查今天是否是开始日期或结束日期的前一天。有任何想法吗?谢谢

4

2 回答 2

4

您可以使用 timedelta 如下:

previous = timezone.now() - timedelta(1)  # returns date object of previous day
next = timezone.now() + timedelta(1)  # returns date object of next day
Inquiry.objects.filter(start_date__lte=previous, end_date__gte=next, status="CO", inquiryequipment__equipment=self)

请注意,您可以使用逗号分隔过滤查询集和查询

于 2018-04-02T09:27:40.210 回答
1
with out date formate

previous = timezone.now() - timedelta(1)  # returns date object of previous day
next = timezone.now() + timedelta(1)  # returns date object of next day
Inquiry.objects.filter(start_date__lte=previous, end_date__gte=next, status="CO", inquiryequipment__equipment=self)

with date formate

previous = (timezone.now() - timedelta(1)).strftime('%Y-%d-%m')  # returns date object of previous day
next = (timezone.now() + timedelta(1)).strftime('%Y-%d-%m')  # returns date object of next day
Inquiry.objects.filter(start_date__lte=previous, end_date__gte=next, status="CO", inquiryequipment__equipment=self)
于 2020-04-07T17:50:19.653 回答