G
G
Gleb2021-02-03 11:38:42
Django
Gleb, 2021-02-03 11:38:42

How to update one column to update others in django?

I have four columns in the database: product name, price per package, quantity per package (grams) and price per gram.
How to make it so that when, for example, the price for one package changes, the price for one gram in UpdateView also changes automatically.
I hope I explained well

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-02-03
@paundaa

Perhaps, of course, this is not a completely correct solution, but it would be possible to override the save () method of the model by adding a calculation per gram

class Product(models.Model):
    name = models.CharField(default='', max_length=50, help_text='Название продукта')
    price = models.IntegerField(default=0, help_text='Цена за упаковку')
    grams = models.IntegerField(default=0, help_text='Количество в упаковке (грамм)')
    price_for_gram = models.IntegerField(default=0, help_text='Цена за грамм')

    def save(self, *args, **kwargs):
        self.price_for_gram = int(self.price / self.grams)
        super().save(*args, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question