将 Django 字段值相乘以获得总计

时间:2021-02-11 15:06:15

标签: django django-models django-views

我有以下型号:

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

我为给定的供应商创建了一个订单对象,其中有两种产品,但数量和成本价格不同。

如何乘以成本 x 数量并将这些值相加以获得总订单价值?

这是我的看法

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)

目前它返回这个:

enter image description here

这是我的html模板

看起来你的帖子主要是代码;请添加更多细节。 好吧,我需要展示我的代码

{% 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 %}

1 个答案:

答案 0 :(得分:1)

costprice 模型中的 Product 字段使用属性装饰器?

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

更新

显然存在一些误解。因此,我会尽量提供更多信息。

第一个问题:“我如何乘以成本 x 数量”

property 装饰器允许您创建字段,其行为类似于计算出的只读字段。 (你不需要初始化它们)

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

第二个问题:“我如何将这些值相加以获得总订单价值?”

您可以使用 Aggregation 来执行此操作。

您可以在视图函数中执行以下操作:

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)

您可以像这样在模板文件中使用 grand_total

{{grant_total}}

希望有帮助