相对于上一个自动增加Django中的值 [英] Auto increment a value in Django with respect to the previous one

查看:48
本文介绍了相对于上一个自动增加Django中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以相对于前一个自动递增字段...例如,如果前一个记录的值是09-0001,那么下一个记录应该分配为09-0002,所以一个...想法?我正在考虑重写save方法,但是我不确定如何

Is there a way to autoincrement a field with respect to the previous one...e.g if the previous record has the value 09-0001, then the next record should be assigned 09-0002 and so one...ideas? I'm thinking of overriding the save method, but how exactly I'm not so sure

推荐答案

Django在模型中不允许您使用多个AutoField,而您的主键已经具有一个.因此,您将不得不覆盖保存,并且可能需要回头看表以找出要增加的内容.

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.

类似这样的东西:

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.

请注意,如果没有对save方法进行某种锁定,则可能会遇到并发问题(两个线程试图在代码和数字中存储相同的值).

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).

这篇关于相对于上一个自动增加Django中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆