Can I have a model field be based on other fields? For example:
class Foo(models.Model):
x = models.PositiveSmallIntegerField()
y = models.PositiveSmallIntegerField()
z = models.PositiveSmallIntegerField()
score = models.PositiveSmallIntegerField(default=x+y+z)
Yes, the best way to handle this would be to override the save
method of the model
class Foo(models.Model):
x = models.PositiveSmallIntegerField()
y = models.PositiveSmallIntegerField()
z = models.PositiveSmallIntegerField()
score = models.PositiveSmallIntegerField()
def save(self, *args, **kwargs):
self.score = self.x + self.y + self.z
super(Foo, self).save(*args, **kwargs) # Call the "real" save() method.
Make sure you take care of the necessary validations.
More on this here: official documentation
How about this?
class Foo(models.Model):
x = models.PositiveSmallIntegerField()
y = models.PositiveSmallIntegerField()
z = models.PositiveSmallIntegerField()
@property
def score(self):
return self.x + self.y + self.z
Official docs on Model Methods here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With