我有一个订阅模型,其中包含created
DateTimeField。订阅自创建之日起持续一年。我还有一个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'
答案 0 :(得分:1)
请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods:
因为您无法在过期设置中使用self.created。
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.
答案 1 :(得分:1)
您的date
计算正在您正在创建的isoformat
实例上调用timedelta
,我怀疑这是您的错误来源。
我认为你只需要一些括号(和self
):
date = (self.created + datetime.timedelta(365)).isoformat()
答案 2 :(得分:0)
假设你在模型上坚持expired
为DateTimeField
,那么你真正想要做的就是覆盖clean
def clean(self):
if self.expired is None:
self.expired = self.created + timedelta(days=365)
return super(Subscription, self).clean()