我有一个 Django 应用程序,我想在其中将一个字段从 ForeignKey 更改为 ManyToManyField。我想保留我的旧数据。为此,最简单/最好的流程是什么?如果重要的话,我使用 sqlite3 作为我的数据库后端。
如果我对问题的总结不清楚,这里有一个例子。假设我有两个模型:
class Author(models.Model):
author = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
假设我的数据库中有很多数据。现在,我想按如下方式更改 Book 模型:
class Book(models.Model):
author = models.ManyToManyField(Author)
title = models.CharField(max_length=100)
我不想“丢失”我之前的所有数据。
完成此任务的最佳/最简单方法是什么?
肯
最佳答案
我意识到这个问题很老,当时数据迁移的最佳选择是使用 South。现在 Django 有自己的 migrate
命令,过程略有不同。
我已将这些模型添加到一个名为 books
的应用程序中——如果不是您的情况,请相应地进行调整。
首先,将字段添加到 Book
并将 related_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:
并向其中添加以下内容。要准确了解其工作原理,请查看 Data Migrations 上的文档.注意不要覆盖迁移依赖项。
# -*- 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()
获得的查询集中。
关于将字段更改为 ManyToMany 时的 Django 数据迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224410/