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

后端 未结 8 1084
小鲜肉
小鲜肉 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: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.

提交回复
热议问题