2π
β
You can override the save
method, since id
is auto generated from database you have to save atleast twice β
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)
but there is one other solution, if you only required the id_hash
for using with python only but not search with it in db, then you do not need to save it, you could use a property
for the hash value like this β
@property
def id_hash(self):
return hashlib.md5(str(self.id)).hexdigest()
π€brainless coder
0π
You want to override the create method for the model, so that the id_hash is written after the initial save. Iβm presuming that you donβt want to write id_hash more than once. For example, maybe something like
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()
Also, you should capitalize your model number (Pick) and probably use unicode instead of str.
π€Mark Chackerian
- [Answered ]-Checking if a URL exists and is smaller than x bytes without consuming full response
- [Answered ]-Remove extra GROUP BY in SQL query in Django ORM
- [Answered ]-Check if member value is different than in previous iteration
- [Answered ]-Django β multiple users with unique data
Source:stackexchange.com