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

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

提交回复
热议问题