开发者

How do I retroactively make AutoFields that don't break django-admin?

I created the models in a Django app using manage.py inspectdb on an existing postgres database. This seemed to work except that all the primary keys were described in the models as IntegerFields, which made them editable in the admin panel, and had to be hand-entered based on knowledge of the id of the previous record. I just learned about this after some usage by the client, so I went back to change things like

blog_id = models.IntegerField(primary_key=True)

...to...

blog_id = models.AutoField(primary_key=True)

Now the id fields don't appear in the admin panel (good), but adding new rows has become impossible (not good).

IntegrityError at /admin/franklins_app/blog/add/

duplicate key value violates unique constraint "blog_pkey"

What's the fix? (Bonus question: is 开发者_高级运维it possible to capture the value that Django is trying to assign as the primary key for the new row?)


The sequence behind the serial field which is your primary key doesn't know about the manually entered records.

Find the maximum value of the primary key:

SELECT MAX(<primary_key>) FROM <your_table>;

Then set the next value of the underlying sequence to a number greater than that:

SELECT SETVAL('<primary_key_seq>', <max_value_in_primary_key_plus_something_for_safety>);

You'll find the name of the sequence (mentioned above as <primary_key_seq>) using:

SELECT pg_get_serial_sequence('<your_table_name>', '<primary_key_column_name');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜