关于Django的总和

时间:2014-12-08 10:12:20

标签: django django-models django-templates

我尝试在聚合中使用Sum但在小计字段上使用错误。该字段属于其他表格。

查看我的代码并查看我的错误。

# models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.db.models import Sum
from django.utils.translation import ugettext_lazy as _
from django.utils.formats import number_format
import locale

locale.setlocale(locale.LC_ALL, '')

...

class Sale(models.Model):
    customer = models.ForeignKey(Customer)
    date_sale = models.DateTimeField(
        _('Data da venda'), auto_now_add=True, auto_now=False)
    modified_at = models.DateTimeField(
        _('Modificado em'), auto_now_add=False, auto_now=True)

    class Meta:
        verbose_name = u'venda'
        verbose_name_plural = u'vendas'

    def _get_total(self):
        s = float(self.sales_det.aggregate(
            subtotal_sum=models.Sum('subtotal')).get('subtotal_sum') or 0)
        return locale.currency(s, grouping=True)
    total = property(_get_total)


class SaleDetail(models.Model):
    sale = models.ForeignKey(Sale, related_name='sales_det')
    product = models.ForeignKey(Product)
    quantity = models.IntegerField(_('quantidade'))
    price_sale = models.DecimalField(
        _('Preço de venda'), default=0, max_digits=8, decimal_places=2)

    def price_sale_formated(self):
        if self.price_sale != None:
            return locale.currency(self.price_sale, grouping=True)
        return ''

    def _get_subtotal(self):
        if self.quantity:
            return self.price_sale * self.quantity
    subtotal = property(_get_subtotal)

    def subtotal_formated(self):
        if self._get_subtotal != None:
            return locale.currency(self._get_subtotal(), grouping=True)
        return ''

在我的模板中,我返回sale.total,但是此字段返回错误,因为未找到小计字段。但小计字段是SaleDetail。

# sale_list.html
{% extends 'base.html' %}

{% block content %}
    <h1>Lista de Vendas</h1>

        <button id="new_sale" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus"></span>
            <a href="{% url 'sale_create' %}"> Nova venda</a>
        </button>

        <div>
            <table class="table">
                <thead>
                    <tr>
                        <th>Cliente</th>
                        <th>Data da venda</th>
                        <th>Itens</th>
                        <th class="text-right">Total</th>
                    </tr>
                </thead>
                <tbody>
                {% for sale in object_list %}

                    <tr>
                        <td><a href="{{ sale.get_detalhe }}">{{ sale.customer }}</a></td>
                        <td>{{ sale.date_sale }}</td>
                        <td>{{ sale.contar }}</td>
                        <td class="text-right">{{ sale.total }}</td>
                    </tr>
                {% empty %}
                    <p>Sem itens na lista.</p>
                {% endfor %}
                </tbody>
            </table>
        </div>
        <div>
            <h3><b>Total:</b> {{ count }}
                {% if count <= 1 %}
                    venda
                {% else %}
                    vendas
                {% endif %}
            </h3>
        </div>

<!-- pagination -->
{% include "_pagination.html" %}

{% endblock content %}

github.com/rg3915/vendas

上查看我的项目

我的错误

enter image description here

我试试这个但不能正常工作

def _get_total(self):
    s = float(self.sales_det.all().aggregate(subtotal_sum=models.Sum(self.sales_det__subtotal)).get('subtotal_sum') or 0)
    return locale.currency(s, grouping=True)
total = property(_get_total)

See my view and models is iet.

# views.py
# -*- coding: utf-8 -*-
from django.views.generic import CreateView, TemplateView, ListView, DetailView
from django.core.urlresolvers import reverse_lazy
from django.template import RequestContext
from .models import Customer, Category, Product, Sale, SaleDetail


class Index(TemplateView):
    template_name = 'index.html'


class About(TemplateView):
    template_name = 'about.html'


class CustomerList(ListView):
    template_name = 'customer_list.html'
    model = Customer
    context_object = 'customer_list'
    paginate_by = 8

    def get_context_data(self, **kwargs):
        context = super(CustomerList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context


class CategoryList(ListView):
    template_name = 'category_list.html'
    model = Category
    context_object = 'category_list'
    paginate_by = 8

    def get_context_data(self, **kwargs):
        context = super(CategoryList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context


class ProductList(ListView):
    template_name = 'product_list.html'
    model = Product
    context_object = 'product_list'
    paginate_by = 8

    def get_context_data(self, **kwargs):

        context = super(ProductList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context


class SaleCreate(CreateView):
    template_name = 'sale_form.html'
    model = Sale
    success_url = reverse_lazy('sale_list')


class SaleList(ListView):
    template_name = 'sale_list.html'
    model = Sale
    context_object = 'sale_list'
    paginate_by = 8

    def get_context_data(self, **kwargs):
        context = super(SaleList, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context


class SaleDetailView(TemplateView):
    template_name = 'sale_detail.html'
    model = Sale

    def get_context_data(self, **kwargs):
        Objvenda = Sale.objects.get(pk=self.kwargs['pk'])
        ItensVenda = SaleDetail.objects.all().filter(sale=Objvenda)
        context = super(SaleDetailView, self).get_context_data(**kwargs)
        context['count'] = ItensVenda.count()
        context['Sale'] = Objvenda
        context['Itens'] = ItensVenda
        return context


class CustomerSearch(ListView):
    template_name = 'search.html'
    model = Customer
    context_object_name = 'lista'
    paginate_by = 8

    def get_context_data(self, **kwargs):
        context = super(CustomerSearch, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context

    def get_queryset(self):
        cObj = Customer.objects.all()
        var_get_search = self.request.GET.get('search_box')
        var_get_order_by = self.request.GET.get('order')

        if var_get_search is not None:
            cObj = cObj.filter(firstname__icontains=var_get_search)

        if var_get_order_by is not None:
            cObj = cObj.order_by(var_get_order_by)

        return cObj

我在github

上的完整代码

2 个答案:

答案 0 :(得分:1)

我解决了 https://github.com/rg3915/vendas/commit/cb8230ee52f10d917305f87f33bc749fd120afbb 感谢。

def get_total(self):
        s = self.sales_det.aggregate(
            subtotal_sum=models.Sum('subtotal')).get('subtotal_sum') or 0
        return s

答案 1 :(得分:0)

您需要在视图代码中获取小计,然后将其作为上下文变量传递给模板