我的模型看起来像这样:
class FoodPreferences(models.Model):
foods = models.ManyToManyField(to='Food', db_index=True,
through='FoodToPreferenceMap')
is_vegan = models.BooleanField(default=True)
some_new_unique_field = models.CharField(max_length=64, unique=True)
现在我想将some_new_unique_field
添加到模型中,但由于它没有默认值,因此迁移会询问我一个新值。该字段应该基于每行的食物值来计算。我该怎么做呢?是否可以设置一个动态计算的默认值?
编辑:
我尝试自定义迁移,这是我的迁移:
def gen_stuff(apps, schema_editor):
MyModel = apps.get_model('myapp', 'foodpreferences')
while MyModel.objects.filter(some_new_unique_field__isnull=True).exists():
with transaction.atomic():
for row in MyModel.objects.filter(some_new_unique_field__isnull=True)[:1000]:
row.some_new_unique_field = row.generate_new_field_stuff()
row.save(update_fields=['some_new_unique_field'])
class Migration(migrations.Migration):
dependencies = [
('stars_api', '0074_foodpreferences_ some_new_unique_field'),
]
operations = [
migrations.RunPython(gen_stuff, reverse_code=migrations.RunPython.noop)
]
但我遇到了
AttributeError: 'FoodPreferences' object has no attribute 'generate_new_field_stuff'
编辑:修正了它,它使用get_model
创建了一个浅表副本答案 0 :(得分:2)
以下是对django doc的建议。你可以尝试一下。简而言之,它说:
new_field
可以为空的迁移; new_field
填充到模型中的每一行;