Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3

After a recent migration from Oracle to Postgres and an upgrade from Django 1.2 to 1.3, we began having problems when saving objects to our database. When save() is called no id is returned, this occurs even when saving the standard django auth models through the standard django admin panel ('/admin/auth/user/None/' is returned even though the user was added to the db and had an id).

All our other sites that run off the same db do not have this problem, however they are running either Django 1.1 or 1.2.

We discovered that for new tables created post-migration their sequence had an 'owned by' attribute that was owned by the column that the sequence was on (usually the id column). Altering the 'owned by' attribute fixed the issues we were having in 1.3.

Does anybody know what the under lying cause for this is? We have found a solution if anyone else is having this issue, but we would love to know what caused it.

like image 348
Iain Shelvington Avatar asked Jun 24 '11 11:06

Iain Shelvington


2 Answers

In postgresql if you own an object you can effectively do anything you want with it. As a result if you are not the owner you will need to grant the user "USAGE" on the sequence.

Postgresql Ownership

Postgresql Grants

like image 153
chotchki Avatar answered May 26 '23 18:05

chotchki


It seems like django probably uses pg_get_serial_sequence to get the sequence associated to the table's column and then currval to get the sequence's current value, but if the sequence is not owned by the table, it's not associated to the column, so it won't work.

The OWNED BY attribute associates a sequence with the given table and column. If a sequence has OWNED BY set to NULL it is essentially a stand-alone sequence, and not really associated in any way to any table or column, and even less associated with a primary key.

like image 43
Giovany Avatar answered May 26 '23 20:05

Giovany