我编写了用于在所有Django应用程序中删除表的python脚本。 (使用settings.INSTALLED_APP)
https://gist.github.com/1520683
我的django项目在运行manage.py syncdb
后创建 41 表,但我的脚本表示只会删除 40 表。所以,我检查了sqlall
的结果和sqlclear
的结果。我透露sqlclear
省略了一个存储ManyToManyField
关系的表。
我知道drop database
比上面的脚本简单得多。但我很困惑为什么django admin或manage script在运行sql命令时省略了一些表。
下面的模型在运行common_userbook_purchasedBooks
时创建syncdb
表,但不在sqlclear
命令中创建。{/ p>
class UserBook(models.Model):
user = models.OneToOneField(User)
purchasedBooks = models.ManyToManyField(Book)
已添加)所以,我正在使用另一种方法。 https://gist.github.com/1520810
答案 0 :(得分:2)
lqez,我认为这个问题与你的本地环境有关,因为对于Django 1.3.1,Python 2.7.2
代表型号
from django.contrib.auth.models import User
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=10)
class UserBook(models.Model):
user = models.OneToOneField(User)
purchasedBooks = models.ManyToManyField(Book)
当我运行(.env)testme$ ./manage.py sqlclear testapp
输出看起来像
BEGIN;
DROP TABLE "testapp_userbook";
DROP TABLE "testapp_userbook_purchasedBooks";
DROP TABLE "testapp_book";
COMMIT;
BEGIN;
ALTER TABLE "testapp_userbook_purchasedBooks" DROP CONSTRAINT "userbook_id_refs_id_8bda4b0";
DROP TABLE "testapp_userbook";
DROP TABLE "testapp_userbook_purchasedBooks";
DROP TABLE "testapp_book";
COMMIT;
BEGIN;
ALTER TABLE `testapp_userbook_purchasedBooks` DROP FOREIGN KEY `userbook_id_refs_id_8bda4b0`;
DROP TABLE `testapp_userbook`;
DROP TABLE `testapp_userbook_purchasedBooks`;
DROP TABLE `testapp_book`;
COMMIT;
使用introspection
:
from django.db import connection
cursor = connection.cursor()
connection.introspection.get_table_list(cursor)
[u'auth_group', u'auth_group_permissions', u'auth_message', u'auth_permission', u'auth_user', u'auth_user_groups', u'auth_user_user_permissions', u'django_content_type', u'django_session', u'django_site', u'testapp_book', u'testapp_userbook', u'testapp_userbook_purchasedBooks']