python 如何让 Django AutoFields 从更高的数字开始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/117800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Django AutoFields to start at a higher number
提问by user9845
For our Django App, we'd like to get an AutoField
to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas?
对于我们的 Django 应用程序,我们希望AutoField
从 1 以外的数字开始。似乎没有明显的方法可以做到这一点。有任何想法吗?
回答by AdamKG
Like the others have said, this would be much easier to do on the database side than the Django side.
就像其他人所说的那样,这在数据库方面比在 Django 方面容易得多。
For Postgres, it'd be like so: ALTER SEQUENCE sequence_name RESTART WITH 12345;
Look at your own DB engine's docs for how you'd do it there.
对于 Postgres,它会是这样:ALTER SEQUENCE sequence_name RESTART WITH 12345;
查看您自己的数据库引擎的文档,了解您在那里如何做。
回答by Gabriel Samfira
For MySQL i created a signal that does this after syncdb:
对于 MySQL,我创建了一个在 syncdb 之后执行此操作的信号:
from django.db.models.signals import post_syncdb
from project.app import models as app_models
def auto_increment_start(sender, **kwargs):
from django.db import connection, transaction
cursor = connection.cursor()
cursor = cursor.execute("""
ALTER table app_table AUTO_INCREMENT=2000
""")
transaction.commit_unless_managed()
post_syncdb.connect(auto_increment_start, sender=app_models)
After a syncdb the alter table statement is executed. This will exempt you from having to login into mysql and issuing it manually.
在同步数据库之后执行更改表语句。这将使您不必登录到 mysql 并手动发出它。
EDIT: I know this is an old thread, but I thought it might help someone.
编辑:我知道这是一个旧线程,但我认为它可能对某人有所帮助。
回答by rh0dium
Here is what I did..
这是我所做的..
def update_auto_increment(value=5000, app_label="remrate_data"):
"""Update our increments"""
from django.db import connection, transaction, router
models = [m for m in get_models() if m._meta.app_label == app_label]
cursor = connection.cursor()
for model in models:
_router = settings.DATABASES[router.db_for_write(model)]['NAME']
alter_str = "ALTER table {}.{} AUTO_INCREMENT={}".format(
_router, model._meta.db_table, value)
cursor.execute(alter_str)
transaction.commit_unless_managed()
回答by William Keller
A quick peek at the sourceshows that there doesn't seem to be any option for this, probably because it doesn't always increment by one; it picks the next available key: "An IntegerField that automatically increments according to available IDs" — djangoproject.com
快速查看源代码表明似乎没有任何选择,可能是因为它并不总是增加 1;它选择下一个可用的键:“根据可用 ID 自动递增的 IntegerField”—— djangoproject.com
回答by S.Lott
The auto fields depend, to an extent, on the database driver being used.
auto 字段在一定程度上取决于正在使用的数据库驱动程序。
You'll have to look at the objects actually created for the specific database to see what's happening.
您必须查看为特定数据库实际创建的对象,以了解发生了什么。
回答by Sean
I needed to do something similar. I avoided the complex stuff and simply created two fields:
我需要做类似的事情。我避免了复杂的东西,只是创建了两个字段:
id_no = models.AutoField(unique=True)
my_highvalue_id = models.IntegerField(null=True)
In views.py, I then simply added a fixed number to the id_no:
在 views.py 中,然后我简单地向 id_no 添加了一个固定数字:
my_highvalue_id = id_no + 1200
my_highvalue_id = id_no + 1200
I'm not sure if it helps resolve your issue, but I think you may find it an easy go-around.
我不确定它是否有助于解决您的问题,但我认为您可能会发现它很容易解决。
回答by micshapicsha
I found a really easy solution to this! AutoField uses the previous value used to determine what the next value assigned will be. So I found that if I inserted a dummy value with the start AutoField value that I want, then following insertions will increment from that value.
我找到了一个非常简单的解决方案!AutoField 使用先前的值来确定分配的下一个值是什么。所以我发现如果我插入一个带有我想要的起始 AutoField 值的虚拟值,那么接下来的插入将从该值开始增加。
A simple example in a few steps:
一个简单的例子,分几步:
1.) models.py
1.) 模型.py
class Product(models.Model):
id = model.AutoField(primaryKey=True) # this is a dummy PK for now
productID = models.IntegerField(default=0)
productName = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
- makemigrations
- migrate
- 迁徙
- 迁移
Once that is done, you will need to insert the initial row where "productID" holds a value of your desired AutoField start value. You can write a method or do it from django shell.
完成后,您将需要插入“productID”保存所需 AutoField 起始值的初始行。您可以编写方法或从 django shell 执行此操作。
From view the insertion could look like this: views.py
从视图中插入可能如下所示:views.py
from app.models import Product
dummy = {
'productID': 100000,
'productName': 'Item name',
'price': 5.98,
}
Products.objects.create(**product)
Once inserted you can make the following change to your model:
插入后,您可以对模型进行以下更改:
models.py
模型.py
class Product(models.Model):
productID = models.AutoField(primary_key=True)
productName = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
All following insertions will get a "productID" incrementing starting at 100000...100001...100002...
以下所有插入都将获得从 100000...100001...100002...开始递增的“productID”。