2👍
✅
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)
Source:stackexchange.com