我意识到这个问题很老了,当时数据迁移的最佳选择是使用 South。现在 Django 有了自己的migrate
命令,过程略有不同。
我已将这些模型添加到一个名为books
-- 如果不是您的情况,请进行相应调整。
首先,将字段添加到Book
和 arelated_name
到至少一个,或者两者都添加(否则它们会发生冲突):
class Book(models.Model):
author = models.ForeignKey(Author, related_name='book')
authors = models.ManyToManyField(Author, related_name='books')
title = models.CharField(max_length=100)
生成迁移:
$ ./manage.py makemigrations
Migrations for 'books':
0002_auto_20151222_1457.py:
- Add field authors to book
- Alter field author on book
现在,创建一个空迁移来保存数据本身的迁移:
./manage.py makemigrations books --empty
Migrations for 'books':
0003_auto_20151222_1459.py:
并在其中添加以下内容。要准确了解其工作原理,请查看有关数据迁移的文档。注意不要覆盖迁移依赖项。
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def make_many_authors(apps, schema_editor):
"""
Adds the Author object in Book.author to the
many-to-many relationship in Book.authors
"""
Book = apps.get_model('books', 'Book')
for book in Book.objects.all():
book.authors.add(book.author)
class Migration(migrations.Migration):
dependencies = [
('books', '0002_auto_20151222_1457'),
]
operations = [
migrations.RunPython(make_many_authors),
]
现在author
从模型中删除该字段——它应该如下所示:
class Book(models.Model):
authors = models.ManyToManyField(Author, related_name='books')
title = models.CharField(max_length=100)
为此创建一个新的迁移,并运行它们:
$ ./manage.py makemigrations
Migrations for 'books':
0004_remove_book_author.py:
- Remove field author from book
$ ./manage.py migrate
Operations to perform:
Synchronize unmigrated apps: messages, staticfiles
Apply all migrations: admin, auth, sessions, books, contenttypes
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying books.0002_auto_20151222_1457... OK
Applying books.0003_auto_20151222_1459... OK
Applying books.0004_remove_book_author... OK
就是这样。以前可用的作者book.author
现在应该在您从中获得的查询集中book.authors.all()
。