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:
p_id
is now 10p_id
10 (again)What is the best way to handle this situation?