Search code examples
pythondjangodjango-models

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


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?


Solution

  • 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 `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 .

    class Order(models.Model):
        add_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,
      `add_date` datetime NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
    +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+