How to add a value from one table to another table with django

1

The point is to make an accounting entry. I'm using the admin of django and when I create a seat I must use two accounts (which already exist in the table account) and those add or subtract the value that entered the seat (total), the thing is that I have been using python for 3 days and django and I do not know if this is possible or there is any way to do it.

This is the models.py

class Asiento(models.Model):
def __str__(self):
    return self.descripcion
id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
fecha = models.CharField(db_column='FECHA', max_length=25, blank=True, null=True)  # Field name made lowercase.
descripcion = models.CharField(db_column='DESCRIPCION', max_length=25, blank=True, null=True)  # Field name made lowercase.
factura = models.CharField(db_column='FACTURA', max_length=25, blank=True, null=True)  # Field name made lowercase.
ctadebito = models.ForeignKey('Cuenta', models.DO_NOTHING, db_column='CTADEBITO', blank=True, null=True, related_name='debito')  # Field name made lowercase.
ctacredito = models.ForeignKey('Cuenta', models.DO_NOTHING, db_column='CTACREDITO', blank=True, null=True, related_name='credito')  # Field name made lowercase.
total = models.FloatField(db_column='TOTAL', blank=True, null=True)  # Field name made lowercase.

class Cuenta(models.Model):
def __str__(self):
    return self.descripcion
codigo = models.IntegerField(db_column='CODIGO', primary_key=True)  # Field name made lowercase.
descripcion = models.CharField(db_column='DESCRIPCION', max_length=25, blank=True, null=True)  # Field name made lowercase.
saldo = models.FloatField(db_column='SALDO', blank=True, null=True)  # Field name made lowercase.
    
asked by Justhine 27.02.2017 в 06:21
source

1 answer

1

Yes, you can do it with a Expression F . Based on the object Asiento you can do something like this:

from django.db.models import F

asiento = Asiento.objects.all().get(id=1)
asiento.ctadebito.saldo = F("saldo") - asiento.total
asiento.ctacredito.saldo = F("saldo") + asiento.total
asiento.ctadebito.save(update_fields=["saldo"])
asiento.ctacredito.save(update_fields=["saldo"])

I used update_fields in the save() method to avoid updating the entire record.

    
answered by 27.02.2017 / 13:33
source