python - 订购时为每个用户创建自动递增编号
问题描述
这是问得最多的问题,但我未能完成这项任务。我有一个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。
使用上面的代码我无法解决这个问题。请提供任何帮助
解决方案
如果要分配一个数字,最好将其设为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)
可能值得包装在原子事务中使用它的视图,以避免由于竞争条件而分配相同的数字。
推荐阅读
- java - JMeter:两个不同线程池的性能测试及其比较
- r - 如何对R中元素包含数字和字母的字符向量进行排序?
- ajax - 如何使用服务器端 ajax 添加页脚总和数据
- pine-script - 我猜tradeview有很大的错误,为什么这段代码不能正确运行
- discord - 我正在尝试创建一个聊天事件,但它不发送消息
- javascript - 单击时隐藏/显示元素
- python - 如何在 pyFirmata 中使用 digitalWrite?
- excel - 询问错误宏 Excell 编译错误:预期:没有类型后缀的标识符
- perl - Perl 在文字字符上拆分字符串 \n
- javascript - 将 css 应用于 input[type=file] 时获取文件名