用于主键自动增量的Django和PostgreSQL序列

时间:2012-04-04 09:57:13

标签: django postgresql

我在postgresql-8.4数据库中有以下表和序列:

CREATE TABLE complexobjectpy
(
  id integer NOT NULL,
  the_geom geometry,
  semcat integer,
  CONSTRAINT complexobjectpy_pkey PRIMARY KEY (id),
  CONSTRAINT enforce_dims_the_geom CHECK (st_ndims(the_geom) = 2),
  CONSTRAINT enforce_srid_the_geom CHECK (st_srid(the_geom) = 900913)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE complexobjectpy OWNER TO tss;

CREATE SEQUENCE seq_complexobjectpy
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;
ALTER TABLE seq_complexobjectpy OWNER TO tss;

以下是我的Django模型:

class Complexobjectpy(models.Model):
    the_geom = models.GeometryField(srid=900913)
    semcat = models.IntegerField()
    objects = models.GeoManager()
    class Meta:
        db_table = u'complexobjectpy'

执行以下查询:

myObj = Complexobjectpy(semcat=50, the_geom=geometryMerged.wkt)
myObj.save(using='u1')

我收到错误:

IntegrityError: null value in column "id" violates not-null constraint

为什么我会这样?阅读文档我希望使用序列...

自动选择id值

1 个答案:

答案 0 :(得分:5)

其实我提供这个作为答案。 postgres中的数据类型serial是一个自动增量的四字节整数。如果你将你的id从整数更改为连续,这将有效。

 id serial NOT NULL

了解详情:http://www.postgresql.org/docs/8.4/static/datatype.html