Python 动态场的Django迁移
我有以下Django模型:Python 动态场的Django迁移,python,django,django-migrations,Python,Django,Django Migrations,我有以下Django模型: class Apple(models.Model): text = models.TextField() 我已经有很多记录了,我想在模型中添加一个主题字段,所以它看起来像: class Apple(models.Model): text = models.TextField() subject = models.CharField(max_length = 128) 。在本例中,我运行makemigrations,但由于subject可以为
class Apple(models.Model):
text = models.TextField()
我已经有很多记录了,我想在模型中添加一个主题字段,所以它看起来像:
class Apple(models.Model):
text = models.TextField()
subject = models.CharField(max_length = 128)
。在本例中,我运行makemigrations,但由于subject可以为空,因此需要在模型或迁移文件中设置默认值
python manage.py makemigrations --empty yourappname
如果我想从已经存在的数据库行(例如:text[:64])的文本中获取主题,那么正确的过程是什么
我的解决方案是使用默认值创建迁移,运行管理命令更新这些值,并使用新迁移删除主题的默认值。有更好的解决办法吗?这是怎么一回事?我能在迁移过程中结合/实现这一点吗
Python:3.4.5
Django:1.9.2对于某些数据库,包括postgresql,添加一个可为空的字段会更快,因此我将您的方法更改为:
null=True
(无需设置默认值)null=True
可以在一个迁移文件中组合这三个操作。但是,数据迁移的Django文档建议您将它们分开。您可以在迁移本身中执行,创建一个迁移文件,在主题字段中使用
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),
]
如果苹果的数据库中有数百万个对象,这将花费太多时间。因此,应该迭代以减少内存使用<代码>苹果.objects.all().iterator()