How to set integer field default to max number +1?

1k Views Asked by At

I used to set the default value of an integer field like this. But with migrations it's not working anymore. What's the proper way to do it?

class Rechnung(models.Model):
  nummer = models.IntegerField(default=lambda: Rechnung.objects.latest('id').nummer + 1)
  [...]
1

There are 1 best solutions below

9
On BEST ANSWER

You can grab this value in the model save method. Save runs for both create and update, so check it's a new object, then set the default if it's new:

class Rechnung(models.Model):
  nummer = models.IntegerField()

  def save(self,*args,**kwargs):
        if self.id != None:
           # new record
           self.nummer = Rechnung.objects.latest('id').nummer + 1)
           super(Rechnung,self).save(*args,**kwargs)

Another way is to replace lambda with a custom function:

def new_num():
   return Rechnung.objects.latest('id').nummer + 1)

class Rechnung(models.Model):
      nummer = models.IntegerField(default=new_num)

Note that you provide the callable as a default, so django calls it each time the default is required (like lambda in the previous version)