Praveen Patil
Praveen Patil

Reputation: 31

Multiplying the values of two objects in Django Models

Hey I'm working with one Django Project, where i wanted to multiply the values of two different objects in django model and storing it to the database.

Here is My code of model

from django.db import models
from django.utils import timezone
from master.models import Supplier

class RawItem(models.Model):
    item_code = models.AutoField(primary_key=True)
    item_name = models.CharField(max_length=100)
    item_price = models.PositiveIntegerField()
    item_Description = models.TextField()

    def __str__(self):
        return self.item_name

class PurchaseOrder(models.Model):
    raw_item = models.ForeignKey(RawItem, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()
    total_prize = models.PositiveIntegerField(editable=False, blank=True, null=True)
    po_date = models.DateTimeField(default=timezone.now)
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        total_prize = self.raw_item.item_price * self.quantity
        super(PurchaseOrder, self).save(*args, **kwargs)

so here i wanted to multiply item_price with quantity how to do that thank you in advance

Upvotes: 2

Views: 529

Answers (2)

Aryan sanchiya
Aryan sanchiya

Reputation: 1

I know the answer is late but i hope still it will be helpful.

--->Views.py

from django.db.models import F

    table = PurchaseOrder.objects.all().update(total_prize = F('raw_item') * F('quantity'))

Upvotes: 0

user8060120
user8060120

Reputation:

To set the total_prize for the current instanse, you should use the self. In your case:

def save(self, *args, **kwargs):
    self.total_prize = self.raw_item.item_price * self.quantity
    #^^^
    super(PurchaseOrder, self).save(*args, **kwargs)

you can read more details understand self in python

and official docs for the class-objects

Upvotes: 2

Related Questions