title: Auto increment django model field per user
body: <p>I have this model:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>What I need is to auto-increment the field <code>number</code> for each separated user. The rationale is that each user has a list of <code>Invoice</code>, starting from <code>number=1</code> to <code>number=latest.number+1</code>.</p>
  
  <p>I do known about <code>F()</code> expressions, but can't figure out how to reference the latest/greatest <code>number</code> for each specific user. Maybe <code>Invoice.objects.filter(owner=request.user).aggregate(Max('number'))</code> is the path, but how do I ensure there is no race conditions between <code>Max()</code> and  <code>F()</code>?</p>