python / 默认 · 1月 16, 2023 0

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

内容纲要

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
%d 博主赞过: