Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i set property data to model field in django

 class Project(models.Model):
   index = models.IntegerField()
   
   @property
   def index(self):
     function = self.function.name
     frac = self.fraction.name
     operation = self.operation.name
     if function == 'Production' and operation == '2C':
        return frac*9
    

What im trying to do is set the returned value from index property to index field.Dont mind the function,frac and operation variables

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ll give you 3 options.

1- You can use the save method to set the value at creation:

class Project(models.Model):
   index = models.IntegerField(null=True, blank=True)

   def save(self, *args, **kwargs):
      if self._state.adding:
         function = self.function.name
         frac = self.fraction.name
         operation = self.operation.name
         if function == 'Production' and operation == '2C':
           self.index = frac*9
    
      super().save(*args, **kwargs)

2- You can simply update the instance without a property:

instance = Project.objects.all()[0]
function = instance.function.name
frac = instance.fraction.name
operation = instance.operation.name
if function == 'Production' and operation == '2C':
   instance.index = frac*9
   instance.save()

3- If you really want to use a property, first you need to change its name to avoid conflicts:

class Project(models.Model):
   index = models.IntegerField()
   
   @property
   def index_value(self):
     function = self.function.name
     frac = self.fraction.name
     operation = self.operation.name
     if function == 'Production' and operation == '2C':
        return frac*9
     else:
        # Returns something else

Then you can assign it to the field:

instance = Project.objects.all()[0]
instance.index = instance.index_value
instance.save()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading