nesu
nesu

Reputation: 35

Multiply Django field values to get a total

I have the following models:

class Supplier(models.Model):

name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)

class Meta:
    ordering = ('name',)

def __str__(self):
    return self.name


class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)

def __str__(self):
    return self.supplier.name

@property
def total(self):
    orderitems = self.product_set.all()
    total = sum([item.get_total for item in products])
    return total

class Product(models.Model):
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(
    null=True, max_length=99, unique=True, blank=True)
supplier = models.ForeignKey(
    Supplier, on_delete=models.CASCADE, default=5)
on_order = models.ForeignKey(
    Order, on_delete=models.CASCADE, null=True, blank=True)
on_order_quantity = models.FloatField(null=True, blank=True)

class Meta:
    ordering = ('description',)

def __str__(self):
    return self.description

i've created an order object for a given supplier with two products, with different quantities and cost prices.

How do I multiply cost x qty and add up those values in order to reach a total order value?

this is my view

def PurchaseOrder(request, pk_order):
orders = Order.objects.get(id=pk_order)
products = Product.objects.filter(
    on_order_id=pk_order).prefetch_related('on_order')
total_products = products.count()
supplier = Product.objects.filter(
    on_order_id=pk_order).prefetch_related('on_order')
total_value = Product.objects.filter(
    on_order_id=pk_order).aggregate(Sum('costprice'))

context = {
    'supplier': supplier,
    'products': products,
    'orders': orders,
    'total_products': total_products,
    'total_value': total_value, }

return render(request, 'crmapp/purchase_order.html', context)

at the moment it returns this:

enter image description here

This is my html template

It looks like your post is mostly code; please add some more details.' Well, I need to show my code

{% extends 'crmapp/base.html' %}
{% load static %}
{% block content %}

<div class='main-site>'>
<h4> Supplier: {{orders.supplier}}</h4>
<h5>Order Number: {{orders.id}}</h5>
<h5>Created on: {{orders.date_created | date:"d/m/Y"}}</h5>
<h6>Total Lines In Order: {{total_products}}</h6>
<button style='margin-bottom:10px' class='btn btn-primary' id="open-popup-1">Edit</button>
<button style='margin-bottom:10px' class='btn btn-success' href=""  id="open-popup-1">Print/Export</button>


      <input type="search" placeholder="Search any field..." class="form-control search-input" data-table="customers-list"/>
      <table class="table table js-sort-table mt32 customers-list" id='myTable'>
      <thead class="table" >
        <tr>
          <th class='header' onclick="sortTable(0)" scope="col">ID</th>
          <th class='header' onclick="sortTable(1)" scope="col">Description</th>
          <th class='header' onclick="sortTable(3)" scope="col">Order Quantity</th>
          <th class='header' onclick="sortTable(2)" scope="col">Cost</th>
        </tr>
      </thead>
      <tbody>
          <tr>
      {% for product in products %}
          <td> <a href="{% url 'productpage' product.id %}">{{product.id}}</a></td>
          <td><h6><strong>{{product.description}}</strong></h6></td>
          <td>{{product.on_order_quantity |floatformat:0}}</td>
          <td>£{{product.costprice |floatformat:2}}</td>
        </tr>
     </tbody>
     {% endfor %}
     
  </table>
  <div class='ordertotal'>
  <h5>Order Value:</h5>
  <h6><strong>{{total_value}}</strong></h6>
  </div>
      
</div>

{% endblock %}

Upvotes: 0

Views: 96

Answers (1)

Michael Haar
Michael Haar

Reputation: 711

Use the property decorator for the costprice field in the Product Model?

class Product(models.Model):
    # define other fields here

    @property
    def costprice(self):
        "Returns retailprice * qty for each product."
        return self.on_order_quantity * self.retailprice

Update:

There's clearly some misunderstanding. Therefore I'll try to provide more information.

First Question: "How do I multiply cost x qty"

The property decorator allows you to create fields, which behave like calculated read_only fields. (You don't need to initialize them)

    @property
    def cost_x_qty(self):
        "Returns costprice multiplied by qty for each product."
        return self.on_order_quantity * self.costprice

Second Question: "How do I add up those values in order to reach a total order value?"

You can use Aggregation to do this.

You can do the following in your view function:

def PurchaseOrder(request, pk_order):
    # some code
    grand_total = Product.objects.filter(
        on_order_id=pk_order).aggregate(Sum('cost_x_qty'))
    # add to context
    context['grand_total'] = grand_total
    return render(request, 'some_template.html', context)

you can use the grand_total in your template file like this:

{{grant_total}}

Hope that helps

Upvotes: 1

Related Questions