1

我有一个带有createdDateTimeField 的订阅模型。订阅自创建之日起持续一年。我也有一个expired领域。不是 100% 确定我是否想将它作为 DateTimeField() 或布尔值。我跑题了。我想要做的基本上是检查/跟踪订阅何时到期。

如果有人能提供任何见解如何做到这一点,我会非常感激。

class Subscription(models.Model):
    user = models.ForeignKey(User)
    subscribed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    expired = models.DateTimeField()

    def expiration(self):
         date = created + datetime.timedelta(365).isoformat()
         return self(expired=date) 

错误:“datetime.timedelta”对象没有属性“isoformat”

4

3 回答 3

1

请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods

更新

因为你不能在 expired 的设置中使用 self.created。

模型.py

class Subscription(models.Model):
    user = models.ForeignKey(User)
    subscribed = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    expired = models.DateTimeField()

    def save(self, *args, **kwargs):
        self.expired = datetime.datetime.now()+datetime.timedelta(365) # original answer used this line: self.created + datetime.timedelta(365).isoformat()
        super(Subscription, self).save(*args, **kwargs) # Call the "real" save() method.
于 2012-08-29T21:12:49.337 回答
1

您的date计算正在调用您正在创建isoformattimedelta实例,我怀疑这是您的错误来自哪里。

我认为您只需要一些括号(和self):

date = (self.created + datetime.timedelta(365)).isoformat()
于 2012-08-29T21:15:13.400 回答
0

假设你要坚持expiredDateTimeField模特,那么你真正想做的就是覆盖clean

def clean(self):
    if self.expired is None:
        self.expired = self.created + timedelta(days=365)
    return super(Subscription, self).clean()
于 2012-08-29T21:24:04.080 回答