Django模型:从模型实例中的其他字段生成字段内容

时间:2017-09-19 19:11:31

标签: python django database

作为一个例子,假设我正在记录库存物品,并且我需要一个唯一的标识符(在自己阅读时也有意义)。

以下显示我正在尝试的模型

class InventoryItem(models.Model):
    item_name = models.TextField(max_length = 100)
    item_manufacturer = models.TextField(max_length = 20)
    item_product_num = models.TextField(max_length = 25)
    item_lot = models.TextField(max_length = 25)
    item_received_on = models.DateTimeField(auto_now_add = True)
    item_price = models.DecimalField()
    item_quantity = models.DecimalField()
    item_special_instructions = models.TextField(default = "NA", max_length = 200)
    item_reinspection_date = models.DateField()

    def makeUniqueID(self):
        unique_str = self.item_manufacturer + self.item_product_num + self.item_lot + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        return unique_str
    item_uniqueID = models.TextField(max_length = 50, default = self.makeUniqueID())

上面的代码错误NameError: name 'self' is not defined,我怀疑这不是正确的方法。 非常感谢任何帮助!

我正在使用的数据库是SQLite,如果它改变了什么

2 个答案:

答案 0 :(得分:2)

我会通过覆盖模型上的保存功能来做到这一点。

class InventoryItem(models.Model):
    #Other Fields
    item_uniqueID = models.TextField(max_length = 50)
    def save(self, *args, **kwargs):
        self.item_uniqueID = self.item_manufacturer + self.item_product_num + self.item_lot + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        super(InventoryItem, self).save(*args, **kwargs)

答案 1 :(得分:1)

可能尝试以下方法:

class InventoryItem(models.Model):
    item_name = models.TextField(max_length = 100)
    item_manufacturer = models.TextField(max_length = 20)
    item_product_num = models.TextField(max_length = 25)
    item_lot = models.TextField(max_length = 25)
    item_received_on = models.DateTimeField(auto_now_add = True)
    item_price = models.DecimalField()
    item_quantity = models.DecimalField()
    item_special_instructions = models.TextField(default = "NA", max_length = 200)
    item_reinspection_date = models.DateField()
    item_uniqueID = models.TextField(max_length = 50)

    def save(self, *args, **kwargs):
        if not self.item_uniqueID:
            self.item_uniqueID = (self.item_manufacturer +
                                  self.item_product_num +
                                  self.item_lot +
                                  datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
            super(InventoryItem, self).save(*args, **kwargs)