【问题标题】:Create a table without rowid with peewee用peewee创建一个没有rowid的表
【发布时间】: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/

谢谢! :)

【问题讨论】:

    标签: python sqlite peewee


    【解决方案1】:

    Peewee 文档也非常清楚如何禁用主键:

    http://docs.peewee-orm.com/en/latest/peewee/models.html#models-without-a-primary-key

    请阅读文档。

    要创建没有主键(与“WITHOUT ROWID”明显不同)的 Peewee 模型,您可以指定“primary_key = False”:

    class NoPKModel(Model):
        key = TextField()
        data = TextField()
        class Meta:
            primary_key = False
    

    不会自动创建一个“id”字段。

    没有 ROWID 是一种具有相当特定用例的 SQLite 优化。使用前请阅读 SQLite 文档并了解 SQLite 数据模型:https://www.sqlite.org/rowidtable.html

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多