How do I make an auto increment integer field in Django?

PythonDjangoDjango Models

Python Problem Overview


I am making an Order model for a shopping cart and I need to make a field that auto increments when the order is made:

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 IntegerField auto increment?

Python Solutions


Solution 1 - Python

In Django

1 : Django model class has default field with name id which is auto increment Field.
2 : You can define your own auto increment field using AutoField field.

class Order(models.Model):
auto_increment_id = models.AutoField(primary_key=True)
# 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 +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 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)
 (
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 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)
 (
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)
 int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 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)
 (
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| 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)
 (
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)
 int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (auto_increment_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

If you want to use django's default id as increment field .

class Order(models.Model):
add_date = models.DateTimeField(auto_now_add=True)

db design

+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 int(11) NOT NULL AUTO_INCREMENT,
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 datetime NOT NULL,
PRIMARY KEY (+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 int(11) NOT NULL AUTO_INCREMENT,
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE core_order (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 (
id int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 int(11) NOT NULL AUTO_INCREMENT,
add_date datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
 datetime NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

Solution 2 - Python

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.

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

Solution 3 - Python

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).

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 AutoField for further details related to AutoField.

Solution 4 - Python

You can create an autofield. Here is the documentation for 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.

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.

Solution 5 - Python

> ### Edited: Fixed mistake in code that stopped it working if there were no YourModel entries in the db.

There's a lot of mention of how you should use an AutoField, and of course, where possible you should use that.

However there are legitimate reasons for implementing auto-incrementing fields yourself (such as if you need an id to start from 500 or increment by tens for whatever reason).

In your models.py

from django.db import models

def from_500():
    '''
    Returns the next default value for the `ones` field,
    starts from 500
    '''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `ones` field and get the largest entry
    largest = YourModel.objects.all().order_by('ones').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 500
        return 500
    # If an instance of `YourModel` is returned, we get it's
    # `ones` attribute and increment it by 1
    return largest.ones + 1

def add_ten():
    ''' Returns the next default value for the `tens` field'''
    # Retrieve a list of `YourModel` instances, sort them by
    # the `tens` field and get the largest entry
    largest = YourModel.objects.all().order_by('tens').last()
    if not largest:
        # largest is `None` if `YourModel` has no instances
        # in which case we return the start value of 10
        return 10
    # If an instance of `YourModel` is returned, we get it's
    # `tens` attribute and increment it by 10
    return largest.tens + 10


class YourModel(model.Model):
    ones = models.IntegerField(primary_key=True,
                               default=from_500)
    tens = models.IntegerField(default=add_ten)

Solution 6 - Python

What I needed: A document number with a fixed number of integers that would also act like an AutoField.

My searches took me all over incl. this page.

Finally I did something like this:

I created a table with a DocuNumber field as an IntegerField with foll. attributes:

  • max_length=6
  • primary_key=True
  • unique=True
  • default=100000

The max_length value anything as required (and thus the corresponding default= value).

A warning is 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.

Afterwards changed the model key field as:

  • Changed the field type as: AutoField
  • Got rid of the max_length And defaultattributes
  • Retained the primary_key = True attribute

The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.

So far so good.

Solution 7 - Python

You can override Django save method official doc about it.

The modified version of your code:

class Order(models.Model):
    cart = models.ForeignKey(Cart)
    add_date = models.DateTimeField(auto_now_add=True)
    order_number = models.IntegerField(default=0)  # changed here
    enable = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        self.order_number = self.order_number + 1
        super().save(*args, **kwargs)  # Call the "real" save() method.

Another way is to use signals. More one:

  1. official Django docs about pre-save
  2. stackoverflow example about using pre-save signal

Solution 8 - Python

You can use default primary key (id) which auto increaments.

Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel SibajaView Question on Stackoverflow
Solution 1 - PythonPrashant GaurView Answer on Stackoverflow
Solution 2 - PythonChitrank DixitView Answer on Stackoverflow
Solution 3 - PythonMushahid KhanView Answer on Stackoverflow
Solution 4 - PythonanuragalView Answer on Stackoverflow
Solution 5 - PythonevantkchongView Answer on Stackoverflow
Solution 6 - Pythonuser5076666View Answer on Stackoverflow
Solution 7 - PythonJasurbek NabijonovView Answer on Stackoverflow
Solution 8 - PythondmvView Answer on Stackoverflow