我的django模型DateField如何添加30天的提供值?

时间:2022-10-04 19:28:14

as the title suggests. I want to add 30 days to the DateField field. This is auto populated on creation of record using auto_now_add=True

正如书名所暗示的。我想在DateField字段中添加30天。使用auto_now_add=True创建记录的自动填充。

Any ideas how to go about doing this?

你知道该怎么做吗?

Thanks

谢谢

5 个解决方案

#1


27  

// Update

/ /更新

The comment under the original post got me thinking. I guess this is the best solution so far:

原帖子下面的评论让我思考。我想这是目前为止最好的解决办法:

from datetime import datetime, timedelta

class MyModel(models.Model):
   mydate = models.DateTimeField(default=datetime.now()+timedelta(days=30))

// 2. Update

/ / 2。更新

If you want to define a model attribute which holds the amount of days that should be added you are going to need to override the save method. So far I could'nt come up with a simpler way.

如果您想要定义一个模型属性来保存应该添加的天数,那么您需要重写save方法。到目前为止,我想不出一个更简单的办法。

Solution:

解决方案:

class MyModel(models.Model):
  mydate = models.DateTimeField(editable=False)
  daysadded = models.IntegerField()

  def save(self):
    from datetime import datetime, timedelta
    d = timedelta(days=self.daysadded)

    if not self.id:
      self.mydate = datetime.now() + d
      super(MyModel, self).save()

As becomingGuru already suggested you should override your models save method.

正如成为guru之前建议的那样,您应该重写模型保存方法。

Example:

例子:

class MyModel(models.Model):
  mydate = models.DateTimeField(auto_now_add=True)      

  def save(self):
    from datetime import timedelta
    d = timedelta(days=30)

    // only add 30 days if it's the first time the model is saved
    if not self.id:
      // not saving the model before adding the timedelta gave me errors 
      super(MyModel, self).save()

      self.mydate += d

      // final save
      super(MyModel, self).save()

This is not the best way for me since you have to save the model twice. But using auto_now_add requires you to save the model first before a datetime instance for mydate is created.

这对我来说不是最好的方法,因为你必须保存模型两次。但是使用auto_now_add需要在创建mydate的datetime实例之前先保存模型。

Another approach which would require only one save:

另一种方法只需要一个保存:

class MyModel(models.Model):
  mydate = models.DateTimeField(editable=False) // editable=False to hide in admin

  def save(self):
    from datetime import datetime, timedelta
    d = timedelta(days=30)

    // only add 30 days if it's the first time the model is saved
    if not self.id:
      self.mydate = datetime.now() + d
      super(MyModel, self).save()

Hope that helped!

希望帮助!

#2


44  

There is no need to implement custom save method.

不需要实现自定义保存方法。

Also doing this default=datetime.now()+timedelta(days=30) is absolutely wrong! It gets evaluated when you start your instance of django. If you use apache it will probably work, because on some configurations apache revokes your django application on every request, but still you can find you self some day looking through out your code and trying to figure out why this get calculated not as you expect.

现在()+timedelta(天数=30)是绝对错误的!它在启动django实例时得到评估。如果您使用apache,它可能会工作,因为在某些配置中,apache会在每个请求上撤销django应用程序,但是您仍然可以找到自己,查看您的代码,并试图找出为什么计算结果不像您期望的那样。

The right way of doing this is to pass a callable object to default argument. It can be a datetime.today function or your custom function. Then it gets evaluated every time you request a new default value.

正确的方法是将可调用对象传递给默认参数。它可以是一个datetime。函数或自定义函数。然后,每当您请求新的默认值时,它都会被评估。

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Bill(models.Model):
    name = models.CharField(max_length=50)
    customer = models.ForeignKey(User, related_name='bills')
    date = models.DateField(default=datetime.today)
    deadline = models.DateField(default=get_deadline)

#3


2  

Use Pythons timedelta:

使用巨蟒timedelta:

from datetime import timedelta
d = timedelta(days=30)

# object is your current instance of the model
object.yourdatefield += d
# or this because I am not sure whether the previous works
object.yourdatefield = object.yourdatefield + d

object.save()

And from the Django documentation:

来自Django文档:

DateField
A date, represented in Python by a datetime.date instance.

DateField一个日期,由一个datetime在Python中表示。日期的实例。

If you want to add 30 days on creation of the object, forget about auto_now_add=True and do as becomingGuru suggests. Information about overriding save() can also be found in the Django documentation.

如果您想在创建对象时增加30天的时间,请忘记auto_now_add=True,并按照becomingGuru的建议执行。关于重写save()的信息也可以在Django文档中找到。

#4


1  

Override the save on the model and while saving, check if pk is populated.

覆盖模型上的保存,并在保存时检查pk是否已填充。

>>> from datetime import datetime
>>> from datetime import timedelta
>>> cur_date = datetime.now()
>>> cur_date
datetime.datetime(2010, 2, 4, 5, 0, 24, 437405)
>>> cur_date+timedelta(days=30)
datetime.datetime(2010, 3, 6, 5, 0, 24, 437405)

#5


-1  

doc for timedelta: https://docs.python.org/2/library/datetime.html

医生为timedelta:https://docs.python.org/2/library/datetime.html

def make_timedelta(seconds):
        return timedelta(days=seconds // 86399, seconds=seconds % 86399)

#1


27  

// Update

/ /更新

The comment under the original post got me thinking. I guess this is the best solution so far:

原帖子下面的评论让我思考。我想这是目前为止最好的解决办法:

from datetime import datetime, timedelta

class MyModel(models.Model):
   mydate = models.DateTimeField(default=datetime.now()+timedelta(days=30))

// 2. Update

/ / 2。更新

If you want to define a model attribute which holds the amount of days that should be added you are going to need to override the save method. So far I could'nt come up with a simpler way.

如果您想要定义一个模型属性来保存应该添加的天数,那么您需要重写save方法。到目前为止,我想不出一个更简单的办法。

Solution:

解决方案:

class MyModel(models.Model):
  mydate = models.DateTimeField(editable=False)
  daysadded = models.IntegerField()

  def save(self):
    from datetime import datetime, timedelta
    d = timedelta(days=self.daysadded)

    if not self.id:
      self.mydate = datetime.now() + d
      super(MyModel, self).save()

As becomingGuru already suggested you should override your models save method.

正如成为guru之前建议的那样,您应该重写模型保存方法。

Example:

例子:

class MyModel(models.Model):
  mydate = models.DateTimeField(auto_now_add=True)      

  def save(self):
    from datetime import timedelta
    d = timedelta(days=30)

    // only add 30 days if it's the first time the model is saved
    if not self.id:
      // not saving the model before adding the timedelta gave me errors 
      super(MyModel, self).save()

      self.mydate += d

      // final save
      super(MyModel, self).save()

This is not the best way for me since you have to save the model twice. But using auto_now_add requires you to save the model first before a datetime instance for mydate is created.

这对我来说不是最好的方法,因为你必须保存模型两次。但是使用auto_now_add需要在创建mydate的datetime实例之前先保存模型。

Another approach which would require only one save:

另一种方法只需要一个保存:

class MyModel(models.Model):
  mydate = models.DateTimeField(editable=False) // editable=False to hide in admin

  def save(self):
    from datetime import datetime, timedelta
    d = timedelta(days=30)

    // only add 30 days if it's the first time the model is saved
    if not self.id:
      self.mydate = datetime.now() + d
      super(MyModel, self).save()

Hope that helped!

希望帮助!

#2


44  

There is no need to implement custom save method.

不需要实现自定义保存方法。

Also doing this default=datetime.now()+timedelta(days=30) is absolutely wrong! It gets evaluated when you start your instance of django. If you use apache it will probably work, because on some configurations apache revokes your django application on every request, but still you can find you self some day looking through out your code and trying to figure out why this get calculated not as you expect.

现在()+timedelta(天数=30)是绝对错误的!它在启动django实例时得到评估。如果您使用apache,它可能会工作,因为在某些配置中,apache会在每个请求上撤销django应用程序,但是您仍然可以找到自己,查看您的代码,并试图找出为什么计算结果不像您期望的那样。

The right way of doing this is to pass a callable object to default argument. It can be a datetime.today function or your custom function. Then it gets evaluated every time you request a new default value.

正确的方法是将可调用对象传递给默认参数。它可以是一个datetime。函数或自定义函数。然后,每当您请求新的默认值时,它都会被评估。

def get_deadline():
    return datetime.today() + timedelta(days=20)

class Bill(models.Model):
    name = models.CharField(max_length=50)
    customer = models.ForeignKey(User, related_name='bills')
    date = models.DateField(default=datetime.today)
    deadline = models.DateField(default=get_deadline)

#3


2  

Use Pythons timedelta:

使用巨蟒timedelta:

from datetime import timedelta
d = timedelta(days=30)

# object is your current instance of the model
object.yourdatefield += d
# or this because I am not sure whether the previous works
object.yourdatefield = object.yourdatefield + d

object.save()

And from the Django documentation:

来自Django文档:

DateField
A date, represented in Python by a datetime.date instance.

DateField一个日期,由一个datetime在Python中表示。日期的实例。

If you want to add 30 days on creation of the object, forget about auto_now_add=True and do as becomingGuru suggests. Information about overriding save() can also be found in the Django documentation.

如果您想在创建对象时增加30天的时间,请忘记auto_now_add=True,并按照becomingGuru的建议执行。关于重写save()的信息也可以在Django文档中找到。

#4


1  

Override the save on the model and while saving, check if pk is populated.

覆盖模型上的保存,并在保存时检查pk是否已填充。

>>> from datetime import datetime
>>> from datetime import timedelta
>>> cur_date = datetime.now()
>>> cur_date
datetime.datetime(2010, 2, 4, 5, 0, 24, 437405)
>>> cur_date+timedelta(days=30)
datetime.datetime(2010, 3, 6, 5, 0, 24, 437405)

#5


-1  

doc for timedelta: https://docs.python.org/2/library/datetime.html

医生为timedelta:https://docs.python.org/2/library/datetime.html

def make_timedelta(seconds):
        return timedelta(days=seconds // 86399, seconds=seconds % 86399)