【发布时间】:2019-06-22 11:19:59
【问题描述】:
我正在创建一个小型 python 程序,并使用 ORM peewee 来管理我的 Sqlite 数据库。我想使用 peewee 创建一个没有主键的表。问题是如果我没有指定一个主键,peewee 正在添加一个主键。阅读文档后,我发现参数 without_rowid 应该阻止 peewee 创建这个主键。但它不起作用。
这是一个小例子的代码:
#!/usr/bin/python
import peewee
import traceback
db_proxy = peewee.Proxy()
class BaseModel(peewee.Model):
class Meta:
database = db_proxy
class table1(BaseModel):
id = peewee.IntegerField(primary_key=True)
field1 = peewee.CharField()
field2 = peewee.IntegerField()
class table2(BaseModel):
table1_id = peewee.IntegerField()
field1 = peewee.CharField()
class Meta:
without_rowid = True
try:
# create database
db = peewee.SqliteDatabase("test.db")
db_proxy.initialize(db)
db.create_tables([table1, table2])
except Exception as e:
traceback.print_exc(e)
与 without_rowid 相同,peewee 会自动将 id 主键添加到我的 table2 表中。这是创建的数据库的架构:
CREATE TABLE IF NOT EXISTS "table1"(
"id" INTEGER NOT NULL PRIMARY KEY,
"field1" VARCHAR(255) NOT NULL,
"field2" INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS "table2"(
"id" INTEGER NOT NULL PRIMARY KEY,
"table1_id" INTEGER NOT NULL,
"field1" VARCHAR(255) NOT NULL
) WITHOUT ROWID;
您知道解决此问题的方法并允许我创建一个没有 rowid 的表吗?
ps:如果你问我为什么要创建一个没有主键的表,那是因为我需要从 csv 文件中插入数据。 (sqlite3 database.db “.mode csv” “.import file.csv table1”)。因为我的表上有一个 AUTO INCREMENT PRIAMRY KEY,所以我需要通过在没有主键的临时表中导入 csv 文件来进行一些技巧,如下所述:http://objectiveme.com/populating-a-sqlite-database-using-csv/
谢谢! :)
【问题讨论】: