Auto increment a value in Django with respect to the previous one

好久不见. 提交于 2019-12-03 03:27:57

Django won't let you have more than one AutoField in a model, and you already have one for your primary key. So you'll have to override save and will probably need to look back at the table to figure out what to increment.

Something like this:

class Product(models.Model): 
   code = models.IntegerField()
   number = models.IntegerField()
   ...

   def get_serial_number(self): 
      "Get formatted value of serial number"
      return "%.2d-%.3d" % (self.code, self.product)

   def save(self): 
      "Get last value of Code and Number from database, and increment before save"
      top = Product.objects.order_by('-code','-number')[0]
      self.code = top.code + 1
      self.number = top.number + 1
      super(Product, self).save()

   # etc.

Note that without some kind of locking in your save method, you can run into a concurrency problem (two threads trying to store the same values in code and number).

AutoField is the field type that Django uses for the model base class' 'id' property, but you can use it for additional autoincremented fields.

I don't think you can do any formatting like in your example, but a good approach would be to make a custom field type that overrides the save() method to perform the desired formatting.

in SQL:

+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| code  | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
+-------+------------------+------+-----+---------+----------------+

In Django:

self.code = None
self.number = top.number + 1
self.save() # or super(Product, self).save()

When saved, the code will be increased automatically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!