Reputation: 107
Is there any way how can I duplicate value to another column,the value should be the same whenever I upload data to column 1 for example. I have 3000
in column 1, the value of column 2 should automatically write 3000
, it is possible to trick in models? or When Inserting query instead using default? Thanks in advance!.
Current output
Column 1 Column 2
5000 5000
3650 5000
2000 5000
Expected output
Column 1 Column 2
5000 5000
3650 3650
2000 2000
models.py
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)
Upvotes: 0
Views: 648
Reputation: 51938
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'))
Upvotes: 1