Coder Peter
Coder Peter

Reputation: 41

Data processing before save in django model

I want to make an automated site in Django model, As an automated if user input unit and quantity it is not good to input also total, I think you understand what I mean it would be. my models looks like this model.py:

    unit_price = models.FloatField(max_length=24)
    quantity = models.FloatField(max_length=24)
    total_price = models.FloatField(max_length=24)

view.py:

    posted = dataForm(request.POST)
    if posted.is_valid():
        posted.save()

what I want is that user inputs quantity and unit_price only and

total_price = quantity * unit_price

So how can I do it ?

Upvotes: 2

Views: 620

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

A ModelForm wraps an .instance that will be saved, you thus can manipulate the .instance object:

posted = dataForm(request.POST)
if posted.is_valid():
    item = posted.instance
    item.total_price = item.quantity * item.unit_price
    posted.save()

That being said, if the total_price is always the quantity times toe unit_price, there is no need to save that in the model, you can calculate that when you need it, or use .annotate(…) [Django-doc] to calculate that at the database side.

Upvotes: 4

Related Questions