如何从python程序重置主键序列

时间:2017-06-23 05:05:49

标签: python django postgresql

How to reset the sequence for IDs on PostgreSQL tables

我知道我可以从terminal重置,但我想从Django python程序重置它。我现在正在尝试使用RAW sql

postgres=# \c uihspot
You are now connected to database "uihspot" as user "postgres".
uihspot=# \dt
                    List of relations
 Schema |             Name             | Type  |  Owner
--------+------------------------------+-------+----------
 public | amway_accessrule             | table | postgres
 public | amway_log                    | table | postgres
 public | auth_group                   | table | postgres
 public | auth_group_permissions       | table | postgres
 public | auth_permission              | table | postgres
 public | auth_user                    | table | postgres
 public | auth_user_groups             | table | postgres
 public | auth_user_user_permissions   | table | postgres
 public | django_admin_log             | table | postgres
 public | django_content_type          | table | postgres
 public | django_migrations            | table | postgres
 public | django_session               | table | postgres
 public | member_profile_memberprofile | table | postgres
 public | ruckus_login_accesslog       | table | postgres
 public | ruckus_login_membertomac     | table | postgres
 public | sales_sales                  | table | postgres
 public | uploaded_files_uploadedfile  | table | postgres
(17 rows)

uihspot=# select currval('sales_sales_id_seq');
ERROR:  currval of sequence "sales_sales_id_seq" is not yet defined in this session
uihspot=# select currval('sales_sales_seq');
ERROR:  relation "sales_sales_seq" does not exist
LINE 1: select currval('sales_sales_seq');
                       ^
uihspot=# select currval('sales_sales_id_seq');
ERROR:  currval of sequence "sales_sales_id_seq" is not yet defined in this session
uihspot=# select currval('uihspot_sales_sales_id_seq');
ERROR:  relation "uihspot_sales_sales_id_seq" does not exist
LINE 1: select currval('uihspot_sales_sales_id_seq');
                       ^
uihspot=# select currval('uihspot.sales_sales_id_seq');
ERROR:  schema "uihspot" does not exist
LINE 1: select currval('uihspot.sales_sales_id_seq');

但我找不到桌子了!

2 个答案:

答案 0 :(得分:0)

万一你可以从外部Python代码(一次性练习)做到这一点: -

您可以使用Pg admin 3(适用于Linux和Windows)。

只需选择数据库,然后执行sql:

ALTER SEQUENCE“my_table_name_id_seq”RESTART WITH 1;

  • 建议:首先尝试复制,然后尝试使用主数据库。

我希望这有用。

答案 1 :(得分:0)

最好的方法

python3 manage.py dbshell
ALTER SEQUENCE "modelName_tableNAme_id_seq" RESTART WITH 1;

这将重新设置 django 模型对象从零(0)开始