I am making an Order
model for a shopping cart and I need to make a field that auto increments when the order is made:
class Order(models.Model)
You can override Django save method official doc about it.
The modified version of your code:
class Order(models.Model):
cart = models.ForeignKey(Cart)
add_date = models.DateTimeField(auto_now_add=True)
order_number = models.IntegerField(default=0) # changed here
enable = models.BooleanField(default=True)
def save(self, *args, **kwargs):
self.order_number = self.order_number + 1
super().save(*args, **kwargs) # Call the "real" save() method.
Another way is to use signals. More one:
In django with every model you will get the by default id field that is auto increament. But still if you manually want to use auto increment. You just need to specify in your Model AutoField
.
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
you can read more about the auto field in django in Django Documentation for AutoField