16👍
✅
We should override save() method.
class TestModel(models.Model):
x = models.CharField(max_length=16)
z = models.CharField(max_length=16)
computed = models.CharField(max_length=32)
def get_computed(self):
result = self.x + self.y
return result
def save(self, *args, **kwargs):
self.computed = self.get_computed()
super(TestModel, self).save(*args, **kwargs)
25👍
class TestModel(models.Model):
x = models.CharField(max_length=16)
z = models.CharField(max_length=16)
computed = models.CharField(max_length=32, editable=False)
def save(self, *args, **kwargs):
self.computed = self.x + self.y
super(TestModel, self).save(*args, **kwargs)
- [Django]-TypeError: count() takes exactly one argument
- [Django]-Execute code when Django starts ONCE only?
- [Django]-Django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
2👍
Firstly, you must have your ‘computed’ field defined in your TestModel. Then when you are creating a new TestModel record, you can compute x + y during record creation and save it.
TestModel.objects.create(x=x_value, y=y_value, computed=(x_value + y_value))
This should do it.
- [Django]-Django FileField: How to return filename only (in template)
- [Django]-Remove Labels in a Django Crispy Forms
- [Django]-Remove "add another" in Django admin screen
Source:stackexchange.com