简体   繁体   中英

Django: How to Set Default Field Value By Model Method

I have a simple Model. I want to calculate a default value for one of its fields (let's call it score) based on some of the fields of the same model :

My ideal way to do it is as so:

class ModelA(models.model):
    field_1 = models.IntegerField()
    field_1 = models.IntegerField()
    score = models.IntegerField(default=self.calculate_default())

    def calculate_default(self):
        default = (self.field_1 + self.field_2) / 2
        return default

Problem : the calculate_default method does not have access to self. One solution I tried was overriding the save() method. The problem is that it prevents the user to further change the score field.

Another method I searched was to override the inti of the class. But according to django it might have consequences if not implemented correctly.

What is the cleanest way to achieve this? How can I set the default of a field to be calculated from other fields of the same model such that it could be later changed by the user?

I have a hunch that classmethod is the way to go but I haven't been able to pull it off yet.

the calculate_default method does not have access to self. One solution I tried was overriding the save() method. The problem is that it prevents the user to further change the score field.

Actually its the right approach. But you can put a check in save() method if the value of score is empty or not:

def save(self, *args, **kwargs):
    if self.score == None:
       self.score = self.calculate_default()
    super().save(*args, **kwargs)

FYI, in classmethod , you can't access self or the ModelA object. If the class method you intend to use is something not dependent on the current instance of ModelA 's fields or totally independent value(for example: current date datetime.now ), then you can use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM