You can simply override the save method:
class Person(models.Model):
amount = models.CharField(max_length=50,blank=True, null=True)
amount_paid = models.CharField(max_length=60,default='5000', null=True)
def save(self, *args, **kwargs):
self.amount_paid = self.amount
super().save(*args, **kwargs)
But there is no need to store duplicate values unless you need it, you can simply add a boolean field, is_paid
and set it True as default.
Also there is a certain pitfall of the given solution, that is if you change the amount, amount_paid will be changed automatically. If you want to update amount_paid if the Person instance is created, then you can add a if else logic:
def save(self, *args, **kwargs):
if not self.pk: # instance not created yet
self.amount_paid = self.amount
super().save(*args, **kwargs)
Alternativly, you can use Django Queryset to update bulk amount of amount_paid
. For example:
from django.db.models import F
Person.objects.filter(pk__in=[1,2,3]).update(amount_paid=F('amount'))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…