私はそうのように見えるモデルがあります:Djangoの既存のモデルに一意のフィールド(空ではない)フィールドを追加するにはどうすればよいですか?
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
を追加したいが、それはデフォルト値の移行がないため、新たな価値のために私を求めるだろう。このフィールドは、各行の食糧値に基づいて計算されるはずです。私はどのようにこれにアプローチすべきですか?動的に計算されるデフォルト値を設定することは可能ですか?
EDIT:
私は、カスタムの移行を試して与え、ここで私の移行だよ:
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'
EDITに実行している:それを修正、それがありましたget_modelを使用して浅いコピーを作成する
あなたは、行ごとに値を計算するために、移行ファイルを編集することができ –
https://docs.djangoproject.com/en/1.11/howto/writing-migrations/#migrations-that-add-uniqueを参照してください。 -fields。 – knbk
@knbk私は自分のカスタムマイグレーションを書きましたが、マイグレーションを実行するときにオブジェクトに実行中の属性エラーはありません –