[英]How do you access the id of a Django model inside the model object?
我有一个简单的模型,我想在其中包含模型ID的哈希值:
class pick(models.Model):
id_hash = models.TextField(default=hashlib.md5(id).hexdigest())
symbol = models.CharField(max_length=5)
buy_datetime = models.DateTimeField()
buy_price = models.DecimalField(max_digits=8, decimal_places=2)
sell_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
buy_quantity = models.IntegerField()
current_price = models.DecimalField(max_digits=8, decimal_places=2)
def hash(self):
return hashlib.md5(str(self.id)).hexdigest()
def __str__(self):
return "{} {} {} {} {} {}".format(self.symbol,self.buy_datetime,self.buy_price,self.sell_price,self.buy_quantity, self.current_price)
当然,对于id_hash,我无法在模型类内部访问id
。 有什么方法可以尝试达到相同的效果?
您可以覆盖save
方法,因为id
是从数据库自动生成的,因此您至少要保存两次-
class pick(models.Model):
id_hash = models.TextField(default="")
symbol = models.CharField(max_length=5)
buy_datetime = models.DateTimeField()
buy_price = models.DecimalField(max_digits=8, decimal_places=2)
sell_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
buy_quantity = models.IntegerField()
current_price = models.DecimalField(max_digits=8, decimal_places=2)
def hash(self):
return hashlib.md5(str(self.id)).hexdigest()
def __str__(self):
return "{} {} {} {} {} {}".format(self.symbol,self.buy_datetime,self.buy_price,self.sell_price,self.buy_quantity, self.current_price)
def save(self, *args, **kwargs):
with transaction.atomic():
super().save(*args, **kwargs)
# for python < 3.0 super(pick, self).save(*args, **kwargs)
self.id_hash = self.hash()
super().save(*args, **kwargs)
# for python < 3.0 super(pick, self).save(*args, **kwargs)
但是还有另一种解决方案,如果您只需要id_hash
仅用于python,而无需在db中搜索它,则不需要保存它,则可以为哈希值使用一个property
,如下所示-
@property
def id_hash(self):
return hashlib.md5(str(self.id)).hexdigest()
您想覆盖模型的create方法,以便在初始保存之后写入id_hash。 我假设您不想多次编写id_hash。 例如,也许像
class PickManager(models.Manager):
def create(**kwargs):
instance = super(PickManager, self).create(**kwargs)
instance.id_hash = hashlib.md5(instance.id).hexdigest()
instance.save()
class Pick(models.Model):
id_hash = models.TextField(blank=True)
...
objects = PickManager()
另外,您应该大写您的型号(Pick),并可能使用unicode而不是str 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.