Search code examples
pythondjangobackend

Merge 2 record in to record when the column datas are the same in django


How can i get the sum of the 'HARMAN' values into 1 record if the 'KARIŞIM KODU' is the same

class ProjeVerileri(models.Model):
    harman = models.CharField(max_length=250,blank=True,null=True)
    karisim = models.CharField(max_length=250,blank=True,null=True)
    def __str__(self):
        return str(self.harman +' / ' + self.karisim)

and this is my model, in the end i want my data to look like this

in the end i want my data to look like this

if request.method == 'POST':
    karisim=request.POST.get('karisim')
    harman=request.POST.get('harman')
    ProjeVerileri.objects.create(
            karisim=karisim,
            harman = harman,
        )

this is my views


Solution

  • The view where you create a ProjectVerileri can be changed to:

    if request.method == 'POST':
        karisim = request.POST.get('karisim')
        harman = request.POST.get('harman')
        item, created = ProjeVerileri.objects.get_or_create(
            karisim=karisim,
            defaults={'harman': harman},
        )
        if not created:
            item.harman += harman
            item.save(update_fields=('harman',))

    so in case the item already exists, we update it.

    If you cleaned the database, i.e. made sure there are no duplicates for karisim anymore, you can also enforce this on the model by marking it unique:

    class ProjeVerileri(models.Model):
        harman = models.CharField(max_length=250, blank=True, null=True)
        karisim = models.CharField(max_length=250, blank=True, null=True, unique=True)
    
        def __str__(self):
            return f'{self.harman} / {self.karisim}'

    Note: It is better to use a Form [Django-doc] than to perform manual validation and cleaning of the data. A Form will not only simplify rendering a form in HTML, but it also makes it more convenient to validate the input, and clean the data to a more convenient type.