Python 如何在 Django 中创建自动递增整数字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21128899/
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 do I make an auto increment integer field in Django?
提问by Daniel Sibaja
I am making an Ordermodel for a shopping cart and I need to make a field that auto increments when the order is made:
我正在Order为购物车制作模型,我需要制作一个在下订单时自动递增的字段:
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeField(auto_now_add=True)
order_number = models.IntegerField()
enable = models.BooleanField(default=True)
How do I make the IntegerFieldauto increment?
如何进行IntegerField自动增量?
采纳答案by pygaur
In Django
在姜戈
1 : There will be a default field with name "id" which is auto increment .
2 : You can define any field as auto increment field using AutoFieldfield.
1:会有一个名为“id”的默认字段,它是自动递增的。
2 :您可以使用AutoField字段将任何字段定义为自增 字段。
class Order(models.Model):
auto_increment_id = models.AutoField(primary_key=True)
#you use primary_key = True if you do not want to use default field "id" given by django to your model
db design
数据库设计
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`auto_increment_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec)
If you want to use django's default id as increment field .
如果你想使用 django 的默认 id 作为增量字段。
class Order(models.Model):
dd_date = models.DateTimeField(auto_now_add=True)
db design
数据库设计
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dd_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
回答by anuragal
You can create an autofield. Here is the documentationfor the same
您可以创建自动字段。这是相同的文档
Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
请记住,Django 不允许一个模型中有多个 AutoField,在您的模型中,您的主键已经有一个(默认)。因此,您必须覆盖模型的 save 方法,并且可能会从表中获取最后插入的记录,并相应地增加计数器并添加新记录。
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
请确保该代码线程安全,因为在多个请求的情况下,您最终可能会尝试为不同的新记录插入相同的值。
回答by dhruven1600
You can use default primary key (id) which auto increaments.
您可以使用自动增加的默认主键 (id)。
Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.
注意:当您使用第一个设计即使用默认字段 (id) 作为主键时,通过提及列名来初始化对象。例如
class User(models.Model):
user_name = models.CharField(max_length = 100)
then initialize,
然后初始化,
user = User(user_name="XYZ")
if you initialize in following way,
如果您按以下方式初始化,
user = User("XYZ")
then python will try to set id = "XYZ" which will give you error on data type.
然后 python 将尝试设置 id = "XYZ" 这会给你数据类型错误。
回答by Chitrank Dixit
In django with every model you will get the by default id field that is auto increament. But still if you manually want to use auto increment. You just need to specify in your Model AutoField.
在每个模型的 django 中,您将获得默认的自动递增的 id 字段。但是如果您手动想要使用自动增量。您只需要在 Model 中指定AutoField。
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
you can read more about the auto field in django in Django Documentation for AutoField
您可以在Django Documentation for AutoField 中阅读有关 django 中自动字段的更多信息
回答by Mushahid Khan
class Belly(models.Model):
belly_id = models.AutoField(primary_key=True)
belly_name = models.CharField(max_length=50)
******** or *******
******** 或者 *******
class Belly(models.Model):
belly_name = models.CharField(max_length=50)
The difference is:
区别在于:
The first table has the primary key belly_id(specified as AutoField) and second table has the primary key id(implicitly).
第一个表具有主键belly_id(指定为AutoField),第二个表具有主键id(隐式)。
I think no need to use this directly; a primary key field will automatically be added to your model if you don't specify. Otherwise
Check the Django Documentation for AutoFieldfor further details related to AutoField.
我觉得没必要直接用这个;如果您不指定,主键字段将自动添加到您的模型中。否则,请查看AutoField的Django 文档以获取与AutoField.
回答by Mushahid Khan
What I needed: A document number with a fixed number of integers that would also act like an AutoField.
我需要的是:具有固定数量整数的文档编号,也可以像AutoField.
My searches took me all over incl. this page.
我的搜索让我遍体鳞伤。这一页。
FinallyI did something like this:
最后我做了这样的事情:
I created a table with a DocuNumberfield as an IntegerField with foll. attributes:
我创建了一个带有DocuNumber字段的表作为 IntegerField with foll。属性:
max_length=6primary_key=Trueunique=Truedefault=100000
max_length=6primary_key=Trueunique=Truedefault=100000
The max_lengthvalue anything as required (and thus the corresponding default=value).
max_length任何需要的值(以及相应的default=值)。
A warningis issued while creating the said model, which I could ignore.
一个警告,同时创造了说模型,我可以不理会发出。
Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.
之后,按预期创建了一个文档(虚拟),该文档的整数字段值为 100000。
Afterwards changed the model key field as:
之后将模型键字段更改为:
- Changed the field type as:
AutoField - Got rid of the
max_lengthAnddefaultattributes - Retained the
primary_key = Trueattribute
- 将字段类型更改为:
AutoField - 去掉了
max_lengthAnddefault属性 - 保留
primary_key = True属性
The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.
创建的下一个(所需文档)的值为 100001,随后的数字递增 1。
So far so good.
到现在为止还挺好。
回答by MoltenMuffins
There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.
有很多关于您应该如何使用 AutoField 的提及,当然,您应该在可能的情况下使用它。
However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need to increment by tens for whatever reason).
但是,您自己实现自动递增字段是有正当理由的(例如,无论出于何种原因,您都需要增加 10 位)。
In your models.py
在你的 models.py
from django.db import models
def add_one():
'''
Returns the next default value for the `ones` field, starts with
500
'''
largest = YourModel.objects.all().order_by('ones').last().ones
if not largest:
return 500
return largest + 1
def add_ten():
''' Returns the next default value for the `tens` field'''
largest = YourModel.objects.all().order_by('tens').last().tens
if not largest:
return 10
return largest + 10
class YourModel(model.Model):
ones = models.IntegerField(primary_key=True,
default=add_one)
tens = models.IntegerField(default=add_ten)

