如何使用新的Django迁移向模型添加新字段? [英] How to add a new field to a model with new Django migrations?

查看:779
本文介绍了如何使用新的Django迁移向模型添加新字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 contribut_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 ,新的字段将添加到您的数据库。为避免处理现有机型的错误,您可以使用 - fake

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. To avoid dealing with errors for your existing models however, you can use the --fake:


  1. 初始化现有模型的迁移:

  1. 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
    

    / li>

  • 再次运行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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆