深度阅读

Django : How to add a new field to a model makemigrations and migrate

作者
作者
2023年08月22日
更新时间
7.87 分钟
阅读时间
0
阅读量

In Django 1.7, in order to add a new field to a model you can simply run ./manage.py makemigrations and ./manage.py migrate and the new field will be added to your DB.

If you want to avoid dealing with errors for your existing models, you can use the – fake :

Initialize migrations for your existing models to include :

./manage.py makemigrations myapp

Validations for existing models for fake migrations:

./manage.py migrate --fake myapp

Add the new field to myapp.model:

from django.db import models

class MyModel(models.Model):
    ... #existing fields
    newfield = models.CharField(max_length=100) #new field

Run makemigrations again

./manage.py makemigrations myapp

Run migrate again:

./manage.py migrate myapp

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。