Auto increases the value in Django compared to the previous one.

Is there a way to auto-increment the field relative to the previous ... for example, if the previous record has the value 09-0001, then the next record must be assigned 09-0002, and therefore one ... idea? I am thinking about overriding the save method, but how exactly am I not sure.

+6
django auto-increment
source share
3 answers

Django will not allow you to have more than one AutoField in the model, and you already have one for your primary key. Thus, you will have to redefine the persistence and probably have to look back at the table to figure out what needs to be increased.

Something like that:

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. 

Please note that without any lock in your save method, you may run into the concurrency problem (two threads try to keep the same values ​​in the code and number).

+8
source share

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

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

+1
source share

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 automatically increments.

0
source share

All Articles