Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

python - Insert duplicate column value in Django

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)
question from:https://stackoverflow.com/questions/65950082/insert-duplicate-column-value-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...