How do I make an auto increment integer field in Django?

后端 未结 8 1067
小鲜肉
小鲜肉 2020-12-02 19:37

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)         


        
相关标签:
8条回答
  • 2020-12-02 20:36

    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:

    1. official Django docs about pre-save
    2. stackoverflow example about using pre-save signal
    0 讨论(0)
  • 2020-12-02 20:37

    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

    0 讨论(0)
提交回复
热议问题