【问题标题】:Django ModelField Add default to based on another field in same model while adding a new fieldDjango ModelField 在添加新字段时基于同一模型中的另一个字段添加默认值
【发布时间】:2016-05-30 14:51:14
【问题描述】:

我有这个字段,

job_created = models.DateTimeField(auto_now_add=True)

现在我想添加类似这样的内容,如何将默认设置基于 post_created 本身。我希望第一个 last_modified 是在创建工作时,我想要类似的东西

last_modified = models.DateTimeField(auto_now=True, default = post_created)

或者如果我在运行迁移时提供一个默认值,该怎么做?

【问题讨论】:

    标签: django django-models django-migrations


    【解决方案1】:

    基本上你不能,但你可以创建一个data migration

    def set_last_modified(apps, schema_editor):
        MyModel = apps.get_model('myapp', 'MyModel')
    
        for obj in MyModel.objects.all():
            obj.last_modified = obj.post_created
            obj.save()
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('myapp', 'previous_migration'),
        ]
    
        operations = [
            # Doesn't need to do anything in reverse, models have not been changed
            migrations.RunPython(set_last_modified, migrations.RunPython.noop)
        ]
    

    您应该通过运行获取此迁移的模板

    migrations --empty yourappname
    

    【讨论】:

      猜你喜欢
      • 2011-05-21
      • 2015-09-26
      • 2016-04-19
      • 2014-12-25
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 2016-05-24
      相关资源
      最近更新 更多