简体   繁体   中英

Create a table without rowid with peewee

I'm creating a small python program and i use the ORM peewee to manage my Sqlite database. I want to create a table without primary key using peewee. The problem is that peewee is adding a primary key if i dont specify one. After read the docs, i found the parameter without_rowid supposed to prevent peewee to create this primary key. But it doesnt works.

Here is a small example of code :

#!/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)

Same with the without_rowid, peewee automatically add an id primary key to my table2 table. Here is the schema of the created database :

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;

Do you know a way to solve this problem and permit me to create a table without rowid ?

ps : if you're asking why i want to create a table without primary key, it's because i need to insert data from a csv file. (sqlite3 database.db ".mode csv" ".import file.csv table1"). As i have an AUTO INCREMENT PRIAMRY KEY on my table, i need to trick a little bit by importing the csv file in a temporary table without primary key as explained here : http://objectiveme.com/populating-a-sqlite-database-using-csv/

Thx ! :)

Peewee documentation is also VERY CLEAR about how to disable primary key:

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

Please READ THE DOCS.

To create a Peewee model without a primary key (which is distinctly different from "WITHOUT ROWID"), you can specify "primary_key = False":

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

This will not automatically create an "id" field.

Without ROWID is a SQLite optimization with rather specific use-case. Please read the SQLite documentation and understand the SQLite data-model before using it: https://www.sqlite.org/rowidtable.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM