我有这种模型形式,在保存时会自动生成Invoice_number。
我的问题:当我更新此模型中的任何字段时,都会生成新的发票编号。
有什么办法可以更新表格并保持原始发票编号不变!
class sale(models.Model):
name = models.CharField(max_length=30,null=True)
contact = models.IntegerField(null=True)
email = models.EmailField(max_length=50,null=True)
Delivery_Date = models.DateField(null=True)
Delivery_time = models.CharField(max_length=80,null=True)
service = models.CharField(max_length=20,null=True)
Invoice_number = models.CharField(max_length=12,blank=True,unique=True)
def save(self, *args, **kwargs):
if self.service == 'Furniture':
x=randint(99,99999)
self.Invoice_number = str('Fur') + str(x)
elif self.service == 'Auto':
x=randint(99,99999)
self.Invoice_number = str('Auto') + str(x)
elif self.service == 'Groceries':
x=randint(99,99999)
self.Invoice_number = str('Gro') + str(x)
super(bookings_modelform,self).save()
答案 0 :(得分:1)
仅在这种情况下,您可以使用save
检入模型的self.pk
方法是否为新对象,并生成发票编号:
def save(self, *args, **kwargs):
if self.pk is None:
if self.service == 'Furniture':
x=randint(99,99999)
self.Invoice_number = str('Fur') + str(x)
elif self.service == 'Auto':
x=randint(99,99999)
self.Invoice_number = str('Auto') + str(x)
elif self.service == 'Groceries':
x=randint(99,99999)
self.Invoice_number = str('Gro') + str(x)
super(bookings_modelform,self).save()
答案 1 :(得分:1)
您可以检查实例是否已经有发票编号,例如:
...
def save(self, *args, **kwargs):
if not self.Invoice_number:
if self.service == 'Furniture':
x=randint(99,99999)
self.Invoice_number = str('Fur') + str(x)
...
话虽如此,您的方法容易出错,因为有时您会因发票编号冲突(由于随机数的性质)而失败,而您的save()
将失败,从而丢失发票。我建议您首先检查该发票号是否曾经使用过。
您还调用了错误的super
(它应该是sale
的超类,而不是bookings_modelform
),即:
super(sale, self).save(*args, **kwargs)