如何使用新的 Django 迁移向模型添加新字段? [英] How to add a new field to a model with new Django migrations?
问题描述
我正在使用 contribute_to_class
方法,但我不知道如何使用新迁移在数据库中创建字段.
I'm using the contribute_to_class
method but I don't know how to create the field in the database with new migrations.
推荐答案
为了回答您的问题,通过 Django 1.7 中引入的新迁移,为了向模型添加新字段,您可以只需将该字段添加到您的模型并使用 ./manage.py makemigrations
初始化迁移,然后运行 ./manage.py migrate
,新字段将添加到您的数据库中.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations
and then run ./manage.py migrate
and the new field will be added to your DB.
然而,为了避免处理现有模型的错误,您可以使用--fake
:
To avoid dealing with errors for your existing models however, you can use the --fake
:
为现有模型初始化迁移:
Initialize migrations for your existing models:
./manage.py makemigrations myapp
现有模型的假迁移:
Fake migrations for existing models:
./manage.py migrate --fake myapp
将新字段添加到 myapp.models:
Add the new field to myapp.models:
from django.db import models
class MyModel(models.Model):
... #existing fields
newfield = models.CharField(max_length=100) #new field
再次运行 makemigrations(这将在将新字段添加到 db 的迁移文件夹中添加一个新的迁移文件):
Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):
./manage.py makemigrations myapp
再次运行迁移:
Run migrate again:
./manage.py migrate myapp
这篇关于如何使用新的 Django 迁移向模型添加新字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!