更改主键 id 的初始值,并在我的模型上从该值开始。

huangapple go评论60阅读模式
英文:

change the initial value of the primary key id, and make start from it on my models

问题

I am working on Django, so I created my table on my models.py. By default when I start registering data, the id, set as primary key, begins with the initial value 1 and increments each time I do a new register.

我正在使用Django,所以我在models.py中创建了我的表。默认情况下,当我开始注册数据时,设置为主键的id从初始值1开始,每次进行新的注册时递增。

I have loaded some data in my table, so the final id right now is 185. I run the server and try to add a new register, but I get an error about id duplicity. Django is trying to save the register in id 1.

我已经在我的表中加载了一些数据,所以当前的最终id是185。我运行服务器并尝试添加一个新的注册,但我收到有关id重复的错误。Django试图将注册保存在id 1上。

How do I get it to continue saving the register from id 186 and onwards?

如何使它继续从id 186开始保存注册?

I tried this on my models:

我在我的模型上尝试了这个:

class MyModel(models.Model):
id = models.AutoField(primary_key=True, initial=123)

but it does not recognize the kwarg initial.

但它不识别initial关键字参数。

英文:

I am working on Django, so I created my table on my models.py. By default when I start registering data, the id, set as primary key, begins with the initial value 1 and increments each time I do a new register.

I have loaded some data in my table, so the final id right now is 185. I run the server and try to add a new register, but I get an error about id duplicity. Django is trying to save the register in id 1.

How do I get it to continue saving the register from id 186 and onwards?

I tried this on my models:

class MyModel(models.Model):
    id = models.AutoField(primary_key=True, initial=123)

but it does not recognize the kwarg initial.

答案1

得分: 0

你可能想使用 sqlsequencereset

你可以在终端中运行它,它会输出用于重置指定模块中每个表的序列的SQL命令。

python manage.py sqlsequencereset <your_app_label>

你可以手动运行生成的SQL命令,或者将它们导入到Django的 dbshell 中以自动运行所有命令。

python manage.py sqlsequencereset <your_app_label> | python manage.py dbshell

有关此主题的更多讨论,请参阅 此问题

英文:

You will likely want to use sqlsequencereset.

You can run it in the terminal and it will output SQL commands for resetting the sequence on every table in the specified module.

python manage.py sqlsequencereset &lt;your_app_label&gt;

You can manually run any generated SQL commands, or you can pipe them into django's dbshell to run all of them automatically.

python manage.py sqlsequencereset &lt;your_app_label&gt; | python manage.py dbshell

See this question for more discussion on this topic.

huangapple
  • 本文由 发表于 2023年2月10日 11:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定