首页 > 解决方案 > 订购时为每个用户创建自动递增编号

问题描述

这是问得最多的问题,但我未能完成这项任务。我有一个Book带有 book_history 字段的模型,例如

class Book(Models):
   customer = models.ForeignKey(Customer)
   book_history_number = models.CharField(max_length=120)

       def _get_book_customer_id(self):
        b_id = self.customer
        num = 1
        while Book.objects.filter(customer=b_id).exists():
            num += 1
        return cus_ord_id

       def save(self, *args, **kwargs):
          if not self.book_history_number:
            self.book_history_number = self._get_book_customer_id()

我的目标是在用户预订某些东西时增加,例如我有 A 和 B 用户以及 A 预订 smth 并且book_history_number应该是 1 下一次应该是 2 像这样:A: 1, 2,... n 因为 A 预订了两次B:0 B 未预订,但如果 B 用户预订,则为 1。

使用上面的代码我无法解决这个问题。请提供任何帮助

标签: pythondjangodjango-modelsdjango-rest-framework

解决方案


如果要分配一个数字,最好将其设为IntegerField. 您还可以计算该Max数字加一的现有书籍的最大数量:

from django.db.models import Max

class Book(Models):
   customer = models.ForeignKey(Customer)
   book_history_number = models.IntegerField(default=0)

   def _get_book_customer_id(self):
       return Book.objects.filter(customer_id=self.customer_id).aggregate(
           numb=Max('book_history_number')+1
       )['numb'] or 0

   def save(self, *args, **kwargs):
       if not self.book_history_number:
           self.book_history_number = self._get_book_customer_id()
       super().save(*args, **kwargs)

可能值得包装在原子事务中使用它的视图,以避免由于竞争条件而分配相同的数字。


推荐阅读