Django模型:相对于其他字段设置默认值 [英] Django models: Set default relative to another field

查看:263
本文介绍了Django模型:相对于其他字段设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.10作为后端来构建应用程序。
是否可以相对于同一实例中的另一个模型设置模型字段的默认值?

I am building an app using Django 1.10 as backend. Is it possible to set a model field's default relative to another model from the same instance?

我特别需要将 second_visit的的默认值设置为 first_visit的3周

I specifically need to set second_visit's default to be 3 weeks after the first_visit

class SomeModel(models.Model): 
    first_visit = models.DateField()
    second_visit = models.DateField(default= second_visit_default)

    def second_visit_default(self):
        # Set second_visit to 3 weeks after first_visit


推荐答案

在拥有模型实例之前,不能在依赖于另一个字段的字段上分配默认值。要实现相同的目的,您可以覆盖模型的 save()方法:

You cannot assign a default value on a field dependent on another before having a model instance. To achieve the same you can override the save() method of the model:

class SomeModel(models.Model):

    ...

    def save(self, *args, **kwargs):
        self.second_visit = self.first_visit + datetime.timedelta(weeks=3)
        super().save(*args, **kwargs)

这篇关于Django模型:相对于其他字段设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆