Ken MacDonald
unread,Nov 19, 2009, 2:57:24 PM11/19/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to django...@googlegroups.com
I have a postgreSQL / psycopg2 DB generated by my Django model with a single user table (normally read-only) that will be updated via batch job about once a week. The PK is the autogenerated 'id' field; however in postgreSQL the generated field is of type 'integer' rather than type 'serial' which is the postgreSQL auto-incrementing type. So, in my batch update job (no Django involved here) I tried to:
INSERT INTO tablename (a, b, c) VALUES ('aa', 'bb', 'cc')
but it complained about a 'duplicate PK error' on id. I found that the sequence 'tablename_id_seq' was not being updated, since it's not a 'serial' field.
What I ended up doing:
First time through the update/insert loop, set the auto-increment sequence counter:
SELECT setval('tablename_id_seq', (SELECT max(id) from tablename))
which ensures that the sequence starts at the proper spot;
then for each INSERT:
INSERT INTO tablename (id, a, b, c) VALUES (nextval('tablename_id_seq'), 'aa', 'bb', 'cc')
So, a couple questions:
1) is it a bug that 'id' is generated as an 'integer' rather than 'serial' type?
2) Is there a way to get Django's model to generate a 'serial' 'id' column that is designated as the PK, so I don't have to explicit specify the 'id' value in my INSERT?
3) Failing that, is there a better way to do the raw SQL steps outlined above?
Thanks,
Ken