Django日期时间比较返回无 - 为什么?

时间:2015-11-18 16:35:58

标签: django datetime comparison

我花了好几个小时试图弄清楚这一点无济于事。不知道为什么会出现这个问题?

models.py

from datetime import date, datetime

class Product(models.Model):
    use_activation_date = models.BooleanField(default=False)
    activation_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True

    @property
    def is_active_by_date(self):
        if self.use_activation_date:
            if datetime.now() < self.activation_date:
                return False #is not active because current date is before activate date
            else:
                return True #is active because date is = or past activation_date
        else:
            return True #is active because not using activation date

template.html

                {% if not product.is_active_by_date %}
              <!-- here is the problem, it is not returning True nor False! -->
                  {{ product.is_active_by_date }} <!-- getting blank result here -->
                  Product is not active 
                {% else %}
                  {{ product.is_active_by_date }}
                  Product is active
                 {% endif %}

发生的问题是,只要product.use_activation_date = True,{{ product.is_active_by_date }}返回True;但是,一旦属性进入日期时间比较行:if datetime.now() < self.activation_date发生错误,并返回None。我尝试打印出datetime.now()和self.activation_date,它们都以相同的格式显示,例如“2015年11月18日,上午10点”一切都很好..

发生什么事了?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

模板引擎可能吞噬了属性中的错误。尝试访问视图中的product.is_active_by_date以查看它返回的内容。

如果您启用了timezone support,则应使用timezone.now()代替datetime.now()

from django.utils import timezone

class Product(models.Model):
    @property
    def is_active_by_date(self):
        if self.use_activation_date:
        if timezone.now() < self.activation_date: