how can i set property data to model field in django

Question:

 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

Asked By: emre_000

||

Answers:

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()
Answered By: Alain Bianchini
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.