T
T
Tobim2021-03-19 20:50:00
Django
Tobim, 2021-03-19 20:50:00

How to change database data by ForeignKey in django?

I have two count tables:

class BankAccount(models.Model):
    TYPE_ACCOUNT = [
        ('Банковский счет', ('Банковский счет')),
        ('Наличные', ('Наличные')),
    ]
    CURRENCY = [
        ('UAN', ('Украинская гривна')),
        ('USD', ('Американский доллар')),
        ('EUR', ('Евро')),
    ]
    type_account = models.CharField("Тип счета", max_length=32, choices=TYPE_ACCOUNT)
    name = models.CharField("Название счета", max_length=250)
    currency = models.CharField("Валюта счета", max_length=32, choices=CURRENCY)
    balance = models.FloatField("Остаток на счете", blank=True, null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=255, unique=False, blank=True, null=True)

Operations:
class Operations(models.Model):
    TYPE_OPERATION = [
        ('Приход', ("Приход")),
        ('Расход', ("Расход")),
    ]
    CURRENCY = [
        ('UAN', ('Украинская гривна')),
        ('USD', ('Американский доллар')),
        ('EUR', ('Евро')),
    ]
    name = models.CharField("Название операции", max_length=255)
    type_operation = models.CharField("Тип операции", max_length=32, choices=TYPE_OPERATION)
    account = models.ForeignKey(BankAccount, on_delete=models.CASCADE)
    sum = models.FloatField("Сума операции")
    currency = models.CharField("Валюта операции", max_length=32, choices=CURRENCY)
    date = models.DateField("Дата проведения операции", default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=255, unique=False, blank=True, null=True)


How to make it so that when saving the operation, the balance of the account to which the operation was attached changes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-19
@Tobim

then when saving the operation, the balance of the account to which the operation was attached would change
They don't do that. It is correct to make a separate explicit function in which an operation is created - write-offs, the balance of the account decreases, a second operation is created - accrual and the balance of the corresponding account increases, well, and most importantly, all this is inside one transaction.
PS and yes, here you can kick hard for
1. FloatField when working with money, right - DecimalField
2. Misunderstandings with the currency of the operation, it should depend on the account or do intermediate conversion operations

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question