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

后端 未结 8 1066
小鲜肉
小鲜肉 2020-12-02 19:37

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)         


        
相关标签:
8条回答
  • 2020-12-02 20:17

    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)
    
    0 讨论(0)
  • 2020-12-02 20:21

    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.

    0 讨论(0)
  • 2020-12-02 20:23

    In Django

    1 : we have default field with name "id" which is auto increment.
    2 : You can define a auto increment field using AutoField field.

    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 .

    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 |
    +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
    
    0 讨论(0)
  • 2020-12-02 20:23

    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.

    0 讨论(0)
  • 2020-12-02 20:24

    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.

    0 讨论(0)
  • 2020-12-02 20:36
    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.

    0 讨论(0)
提交回复
热议问题