如何基于相同模型的另一个字段更新模型字段

时间:2019-02-19 05:45:30

标签: django django-models django-forms django-views locust

class PurchaseOrder(models.Model):
   purchase_order_id = models.AutoField(primary_key=True)  
   purchase_order_number = models.CharField(unique=True)
   vendor = models.ForeignKey(Vendor)

我正在创建采购订单(po)表。创建po时,我必须将purchase_order_number更新为PO0123的“ PO0” + purchase_order_id(123是主键)。所以我在模型中使用def save来完成此任务

def save(self):
    if self.purchase_order_id is not None:
        self.purchase_order_number = "PO"+str(self.purchase_order_id)
    return super(PurchaseOrder, self).save()

它可以很好地进行单个创建,但是当我尝试使用locust(测试工具)创建大量数据时,它会给出错误duplicate entry for PurchseOrdernumber我们可以在模型本身中修改字段值吗?

purchase_order_number = models.CharField(unique=True,default=("PO"+self.purchase_order_id )

1 个答案:

答案 0 :(得分:0)

说实话,当您创建多个实例时,我认为它不起作用。因为从代码中可以看到:

if self.purchase_order_id is not None:
    self.purchase_order_number = "PO"+str(self.purchase_order_id)

在创建新实例时,purchase_order_id将为None。此外,在您调用super(PurchaseOrder, self).save()之前,它将不会生成purchase_order_id,这意味着purchase_order_number将为空。

因此,我建议不要在DB中存储此信息。它与purchase_order_id基本相同,前面是PO。相反,您可以使用属性方法来获取相同的值。像这样:

class PurchaseOrder(models.Model):
   purchase_order_id = models.AutoField(primary_key=True)
   # need to remove `purchase_order_number = models.CharField(unique=True)`
   ...

   @property 
   def purchase_order_number(self):
       return "PO{}".format(self.purchase_order_id)

因此,您还可以看到purchase_order_number,如下所示:

p = PurchaseOrder.objects.first()
p.purchase_order_number

该解决方案的缺点是,您不能在属性字段上输入任何query。但我认为仍然没有必要,因为您可以对purchase_order_id,即PurchaseOrder.objects.filter(purchase_order_id=1)进行相同的查询。