![](/img/trans.png)
[英]django migration is not creating all the fields from defined model class into db
[英]Django migration from dynamic fields
我有以下Django模型:
class Apple(models.Model):
text = models.TextField()
我已經有很多記錄,並且想在模型中添加一個主題字段,因此它看起來像:
class Apple(models.Model):
text = models.TextField()
subject = models.CharField(max_length = 128)
。 在這種情況下,我運行makemigrations,但是由於subject可以為空,因此我需要在模型或遷移文件中設置默認值。
如果我想從已經存在的數據庫行的文本中獲取主題(例如:text [:64]),正確的程序是什么?
我的解決方案是使用默認值創建遷移,運行管理命令以更新值,然后使用新遷移刪除主題的默認值。 有更好的解決方案嗎? 它是什么? 我可以在遷移本身中以某種方式進行組合嗎?
的Python:3.4.5的Django的:1.9.2
對於某些數據庫(包括postgresql),可以更快地添加一個可為空的字段,因此我將更改您的方法:
null=True
創建字段(無需設置默認值) null=True
您可以將三個操作合並到一個遷移文件中。 但是,用於數據遷移的Django文檔建議您將它們分開。
您可以在遷移本身中完成此操作,在主題字段中創建一個blank=True, null=True
文件blank=True, null=True
的遷移文件。
class Apple(models.Model):
text = models.TextField()
subject = models.CharField(max_length=128, blank=True, null=True)
然后創建另一個空的遷移文件。
python manage.py makemigrations --empty yourappname
將以下代碼粘貼到該文件中。
from django.db import migrations
def set_subject(apps, schema_editor):
Apple = apps.get_model('yourappname', 'Apple')
for a in Apple.objects.all():
a.subject = a.text
a.save()
class Migration(migrations.Migration):
dependencies = [
('yourappname', 'name of above migration file'),
]
operations = [
migrations.RunPython(set_subject),
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.