Home > Enterprise >  Value returned by property method in django not getting stored in database. How to make this possibl
Value returned by property method in django not getting stored in database. How to make this possibl

Time:11-21

In my models.py file I have a property method which returns a value and I need to store that value in the database field.

`

class bug(models.Model):
    ......
    .......
    id_of_bug = models.CharField(max_length=20, blank= False, null= False)
    
    @property
    def bug_id(self):
        bugid = "BUG{:03d}".format(self.pk)
        self.id_of_bug = bugid
        return bugid




Tried to store the value in database using self method, but not working.

CodePudding user response:

I would try use a property setter that updates the table value:

class bug(models.Model):
    ......
    .......
    id_of_bug = models.CharField(max_length=20, blank= False, null= False)
    
    @property
    def bug_id(self):
        bugid = "BUG{:03d}".format(self.pk)
        self.id_of_bug = bugid
        return bugid

    @bug_id.setter
    def bug_id(self, value):
        # value = some_transform(value)
        self.id_of_bug = value
        self.save(update_fields=['id_of_bug'])

CodePudding user response:

Try signals to store data

class bug(models.Model):
    ......
    .......
    id_of_bug = models.CharField(max_length=20, blank= False, null= False)
    
    @property
    def bug_id(self):
        bugid = "BUG{:03d}".format(self.pk)
        return bugid


from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=bug)
def save_bugid(sender, instance,created, **kwargs):
    if created:
        instance.id_of_bug = instance.bug_id
        instance.save()
  • Related