postgresql - Django AutoField not returning new primary_key -


we've got small problem django project we're working on , our postgresql database.

the project we're working on site/db conversion php site django site. used inspect db generate models current php backend.

it gave , added primary_key , unique equals true:

class company(models.model):      companyid = models.integerfield(primary_key=true,unique=true)      ...      ... 

that didn't seem working when got saving new company entry. return not-null constraint error, migrated autofield below:

class company(models.model):      companyid = models.autofield(primary_key=true)      ...      ... 

this saves company entry fine problem when do

result = form.save() 

we can't

result.pk or result.companyid 

to newly given primary key in database (yet can see has been given proper companyid in database.

we @ loss happening. ideas or answers appreciated, thanks!

i ran same thing, during django upgrade of project lot of history. pain...

anyway, problem seems result way django's postgresql backend gets primary key newly created object: uses pg_get_serial_sequence resolve sequence table's primary key. in case, id column wasn't created serial type, rather integer, means sequence isn't connected table.column.

the following based on table create statement, you'll have adjust table names, columns , sequence names according situation:

create table "mike_test" (   "id" integer not null primary key,   "somefield" varchar(30) not null unique ); 

the solution if you're using postgresql 8.3 or later pretty easy:

alter sequence mike_test_id_seq owned mike_test.id; 

if you're using 8.1 though, things little muckier. recreated column following (simplest) case:

alter table mike_test add column temp_id serial not null; update mike_test set temp_id = id; alter table mike_test drop column id; alter table mike_test add column id serial not null primary key; update mike_test set id = temp_id; alter table mike_test drop column temp_id; select setval('mike_test_id_seq', (select max(id) mike_test)); 

if column involved in other constraints, you'll have more fun it.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -