0

如果确认 == True,我正在尝试让我的程序生成这个唯一编号。

class PurchaseOrder(models.Model):
    po_number = models.IntegerField(unique=True)
    confirmed = models.NullBooleanField(null=True)

 def save(self, *args, **kwargs):
    if not self.pk:
        self.po_number = self.validPONumber()
    super(PurchaseOrder, self).save(*args, **kwargs)

def validPONumber(self):
     low= 50000
     high =1000000
     random.seed()
     value = random.randrange(low, high)
     while 0 < len(PurchaseOrder.objects.filter(po_number=value)):
        value = random.randrange(low, high)
     return value

因此,基本上只有在确认 == True 时才会生成 po_number。我尝试在随机位置插入逻辑,但它会产生错误。我应该把它放在哪里?

4

1 回答 1

2

我认为把它放在方法中是有意义的save

def save(self, *args, **kwargs):
    if not self.pk and self.confirmed:
        self.po_number = self.validPONumber()
    super(PurchaseOrder, self).save(*args, **kwargs)

这将指定记录必须是新的并且confirmed == True

您是否希望它只从新记录中生成?您希望在更新记录时进行检查吗?如果是这样,您可以在每次save调用该方法时设置它:

def save(self, *args, **kwargs):
    if self.confirmed:
        self.po_number = self.validPONumber()
    super(PurchaseOrder, self).save(*args, **kwargs)
于 2013-08-06T14:45:07.317 回答