1

I have a table in my PostgreSQL:

CREATE SEQUENCE dember_id_seq INCREMENT BY 1 MINVALUE 1 START 1;
CREATE TABLE dember (id INT NOT NULL, did VARCHAR(255) DEFAULT NULL, dnix VARCHAR(255) DEFAULT NULL, durl TEXT DEFAULT NULL, created TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, modified TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, status BOOLEAN NOT NULL, dnickname VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id));

When I want to insert a record, I using the following code:

import pg
db = pg.DB(....)
db.insert('dember',{'did':did,'dnix':dnix,'durl',durl,'created',now, 'modified':now, 'status':'true','dnickname':nickname'})

Then the insert code does not work, I get the following error:

pg.ProgrammingError: ERROR: null value in column "id" violates not-null constraint

It looks that I have to add {'id':number} to the value dictionary.

Any suggestions? Thanks.

2 Answers 2

3

You should save yourself some trouble and use serial instead of int:

The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).

So saying:

create table t (
    id serial not null primary key
    -- ...
)

will create id as an integer column, create a sequence for it, set the default value of id to be the next value in the sequence, and set the sequence's owner to the id column; the last bit is important, the implied

ALTER SEQUENCE t_id_seq OWNED BY t.id;

that a serial type does ensures that the sequence will be dropped when the column goes away. If you don't set the sequence's owner, you can be left with dangling unused sequences in your database.

Sign up to request clarification or add additional context in comments.

Comments

1

You forgot to assign the sequence to the column.

CREATE TABLE dember (id INT NOT NULL DEFAULT nextval('dember_id_seq'), ...

1 Comment

CREATE TABLE dember (id INT NOT NULL DEFAULT nextval('dember_id_seq'), did VARCHAR(255) DEFAULT NULL, dnix VARCHAR(255) DEFAULT NULL, durl TEXT DEFAULT NULL, created TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, modified TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, status BOOLEAN NOT NULL, dnickname VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.