如何在Django中删除数据库表?

5

我修改了我的模型并进行了数据库迁移。然后我再次修改了我的模型,但在尝试运行python manage.py migrate时出现错误:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, shop
Running migrations:
  Applying shop.0004_auto_20180128_1331...Traceback (most recent call last):
  File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
  File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 301, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "shop_brand" already exists

所以我的问题是 - 如何删除表 "shop_brand"??? 我已经尝试过flushsqlflush,但这只会从表中删除数据而不是实际的表 "shop_brand"。 我使用django 2.0.1和python 3.6。

请查看这个链接 - Laurynas Tamulevičius
只删除所有文件是一个选项,但我想知道如何仅在数据库中删除一个表。 - Loctarogar
1个回答

22

使用dbshell命令

python manage.py dbshell

然后在shell中,根据您使用的数据库,键入命令以显示表格以识别要删除的表格。

例如,对于sqlite,您将使用

.tables

仍在shell中,您可以使用SQL命令来删除表格。

DROP TABLE shop_brand;

我尝试了,但出现了CommandError错误:您似乎没有安装“sqlite3”程序或将其加入到路径中。 - Loctarogar
请查看 https://dev59.com/cloU5IYBdhLWcg3wnX1O。 - Kevin L.
或者安装sqlite3 sudo apt-get install sqlite3 - Kevin L.
好的,我会尝试。我只是认为我可以仅使用Django来处理它。 - Loctarogar
为什么我在管理站点中仍然看到那些已删除的表格呢? :( - Gakuo
2
我无法通过makemigrations或migrate来恢复表。 - Fathy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接