Django Item模型保存时按Location编码生成系列号拼接property_number
你现有代码的核心错误
- 过滤查询写法错误:把Python判断表达式直接写在
filter()里,而不是用Django ORM支持的跨表查询语法,导致查询结果完全不符合预期 - 没有区分新增/编辑场景:如果在Admin里修改已存在的Item,代码会重新计算系列号,篡改已经生成好的property_number
- 计数逻辑没有防并发保护:多个管理员同时新增同location的Item时,会出现重复的系列号
- 没有做4位格式补位:直接返回数字1、2,没有转成0001、0002的字符串格式
可直接使用的修正实现
所有原有字段完全不用改动,只需要在Item模型里补充修正后的save和系列号生成方法,记得先导入事务模块:from django.db import models, transaction
class Item(models.Model): # 这里完全保留你原来写的所有字段定义,不做任何修改 item = models.CharField(max_length=100, null=True) description = models.TextField(max_length=200, null=True) date_acquired = models.DateField(null=True) old_property_number = models.CharField(max_length=100, null=True) property_number = models.CharField(max_length=100, null=True, blank=True) unit_of_measure = models.ForeignKey('Uom', related_name='uom_item', null=True, on_delete=models.SET_NULL) unit_value = models.DecimalField(max_digits=12, decimal_places=2, null=True) quantity_per_card = models.CharField(max_length=100, null=True, default='1') quantity_per_physical_count = models.CharField(max_length=100, null=True, default='1') location = models.ForeignKey('Location', related_name='location_item', null=True, on_delete=models.SET_NULL) condition = models.ForeignKey('Condition', related_name='condition_item', null=True, on_delete=models.SET_NULL) accountable_person = models.ForeignKey('Personnel', related_name='personnel_item', null=True, on_delete=models.SET_NULL) remarks = models.ForeignKey('Remarks', related_name='remarks_item', null=True, on_delete=models.SET_NULL) sub_major_group_and_gl_account = models.ForeignKey('Account', related_name='sub_major_group_and_gl_account_item', null=True, on_delete=models.SET_NULL) def generate_series_number(self): with transaction.atomic(): # 跨表查询:匹配所有和当前记录同location_code的已存Item,加锁防止并发重复 same_location_items = Item.objects.select_for_update().filter( location__location_code=self.location.location_code ) # 计算下一个系列号,格式化为4位字符串,不足位数前面补0 next_series = str(same_location_items.count() + 1).zfill(4) return next_series def save(self, *args, **kwargs): # 仅在新增记录、且property_number为空时自动生成编号,编辑原有记录时不改动已生成的编号 if not self.pk and not self.property_number: series_num = self.generate_series_number() # 按需求格式拼接property_number self.property_number = '{}-{}-{}-{}'.format( self.date_acquired.year, self.sub_major_group_and_gl_account.sub_major_group_and_gl_account, series_num, self.location.location_code ) super().save(*args, **kwargs)
实现效果说明
- 完全匹配你的计数规则:同一location_code下的Item依次按0001、0002递增,不同location_code的计数完全独立,互不干扰
- 不会篡改已有数据:在Admin里修改已存在的Item的其他字段时,不会重新计算系列号、覆盖已有的property_number
- 自动补位格式:数字5会自动转成0005,1000会正常显示为1000,满足4位系列号的格式要求
- 并发安全:通过事务+行锁机制,避免多个管理员同时新增Item时出现重复系列号的问题
注意:因为你设置location为可空字段,如果新增Item时没有选择关联Location,生成系列号的逻辑会报错,你可以根据业务需要在生成系列号前加判断:如果self.location为None,就跳过自动生成或者给默认值即可。
内容的提问来源于stack exchange,提问作者Markmeplease
相关产品推荐
相关产品推荐

