[Answered ]-How do you access the id of a Django model inside the model object?

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()

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.

Leave a comment