问题
I have this model:
class Invoice(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
data = models.TextField(default=None, blank=True, null=True)
number = models.PositiveIntegerField(default=0, null=False)
What I need is to auto-increment the field number
for each separated user. The rationale is that each user has a list of Invoice
, starting from number=1
to number=latest.number+1
.
I do known about F()
expressions, but can't figure out how to reference the latest/greatest number
for each specific user. Maybe Invoice.objects.filter(owner=request.user).aggregate(Max('number'))
is the path, but how do I ensure there is no race conditions between Max()
and F()
?
回答1:
You can achieve this and similar functions by overriding save method in model and writing your custom logics to it.
class Invoice(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
data = models.TextField(default=None, blank=True, null=True)
number = models.PositiveIntegerField(default=0, null=False)
def save(self, *args, **kwargs):
if self.pk:
self.number += 1
# Write all your logic here, like handeling max value etc
return super(Invoice, self).save(*args, **kwargs)
来源:https://stackoverflow.com/questions/33922447/auto-increment-django-model-field-per-user