Django model integer increment, unique together

时间:2015-09-14 15:21:21

标签: django django-models

I am wanting to have the following on a model: Each time a "item" (called product) is added by a particular user I want to increment that users product ID (p_id) by one. This is different to the primary key which will increment by one for each product added no matter who the user is. My initial thought was to use AutoField but this works on the entire model.

The model will be something like:

class Product(models....):
    name = models.CharField(max_....)
    p_id = models.AutoField()
    user = models.ForeignKey(....)

    class Meta:
        unqiue_together = ('user', 'p_id')

Seeing as this will not work my next thought was to override save. To do something like.

def save(self, *args, **kawrgs):
    product_count = get_product_count_for_user()
    self.p_id = product_count+1
    super().save()

The problem here is that when a user deletes a Product the count can then become wrong for future saves.

For example:

  • User adds item p_id is now 10
  • User deletes an old item
  • User adds item when I do get product count 9 is now returned
  • New item is saved with p_id 10 (again)

What is the best way to handle this situation?

0 个答案:

没有答案