我有这个领域,
job_created = models.DateTimeField(auto_now_add=True)
现在我想添加这样的东西,如何将默认值基于post_created本身。我希望第一个last_modified是在创建作业时,我想要像
这样的东西last_modified = models.DateTimeField(auto_now=True, default = post_created)
或者,如果我在运行迁移时提供一个默认值,该怎么做?
答案 0 :(得分:5)
基本上你不能,但你可以创建一个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