Search code examples
pythonpostgresqlpython-2.7peewee

Python Peewee not creating unique constraints in postgres


I'm creating my schema by using this snippet of code:

from peewee import *

db = PostgresqlDatabase('db', user='user', password='pass', host="localhost")

class Actor(Model):
    name = TextField(unique=True)

db.create_table(Actor)

Unfortunately, peewee doesn't seem to add UNIQUE constraints.

Output SQL:

-- Table: actor

-- DROP TABLE actor;

CREATE TABLE actor
(
  id serial NOT NULL,
  name text NOT NULL,
  CONSTRAINT actor_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE actor
  OWNER TO user;

And in fact I can add multiple rows with the same name.

Any idea of what's going wrong? Thank you all very much in advance :)

I'm using postgres 9.3.10 if that matters... python 2.7.6, peewee 2.6.4 (tried different versions, though).


Solution

  • You should use the Model.create_table() API, which handles creating table and indexes.

    Alternatively, you can call db.create_tables(), which resolves model dependencies and creates multiple tables (and indexes) in the appropriate order.

    db.create_table(), the API You're using, just creates the table itself -- no indexes.

    So:

    db.create_tables([Actor])
    

    Or:

    Actor.create_table()