0

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)
5
  • refer this ans : stackoverflow.com/a/4381252/1079086 Commented Jan 29, 2021 at 7:01
  • If the columns should be on sync why the 2nd column? Commented Jan 29, 2021 at 7:02
  • @Klaus D. Yes, second column should be the same in first column,eg amount _paid should the same value in amount Commented Jan 29, 2021 at 7:02
  • @MarieLoise : As mentioned in link i have shared. you can overwrite your save method which will take information from first column and assign it to second column Commented Jan 29, 2021 at 7:03
  • But why do you need a second column? You could just use the first one. It has the same value. Commented Jan 29, 2021 at 7:04

1 Answer 1

1

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'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.