As an example, say I'm logging inventory items, and I need a unique identifier (that is also meaningful when read by itself) for each item.
The following shows the model I am trying
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())
The above code errors NameError: name 'self' is not defined
, and I suspect this is not the correct way to do this. Any help is greatly appreciated!
The database I'm using is SQLite if that changes anything
I would do this by overriding the save function on the model.
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)
Possibly try the following:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.