Auto increment django model field per user

…衆ロ難τιáo~ 提交于 2020-12-30 06:36:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!