本文介绍了Django在syncdb时以自定义方式初始化数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发过程中使用Django。这是恼人的,每次我改变一个模型中的一点,我需要删除数据库和运行syncdb。为了测试的目的,我想每次当我运行syncdb时,自动添加一些初始数据到数据库。我试过把这些代码放在一个应用程序的 __ init __。py ,但它会在数据库创建之前运行,这是一个有点恼人的处理异常。

I'm using Django in a development process. It is annoying that every time I change a bit in a model I need to delete database and run syncdb. For the purpose of testing, I want to add some initial data into database automatically every time when I run syncdb. I've tried put these sort of code inside one app's __init__.py, but it would run before database created and it's a bit annoying to deal with exceptions. Isn't there a neater way to do this?

推荐答案

一旦你最初填充了数据库,请使用命令创建fixture(数据的副本)。将其保存到文件。然后使用命令自动填充数据库。

Once you have initially populated the database; use the dumpdata command to create a fixture (a copy of data). Save it to a file. Then use the loaddata command to automatically populate the database.

假设您有一个名为 bookstore的应用程序

一旦您在数据库中添加了一些记录:

Once you have added some records in the database:

python django-admin.py dumpdata bookstore > initial.json

一旦您进行了某些更改或要重新创建数据库:

Once you have made some changes or want to recreate the database:

python django-admin.py loaddata initial.json

南是好的,但是为了这个目的是过度的。

South is nice, but it is overkill for this purpose.

这篇关于Django在syncdb时以自定义方式初始化数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 15:28