Stack Exchange
Aggregate Sum on Django
I try use Sum in aggregate but error on subtotal field. This field is of other table.
See my code and see my error.
# 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 ''

And in my template i return sale.total, but this field return error because subtotal field not found. But subtotal field is 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 %}

See my project on the github.com/rg3915/vendas
And my error

I try this but not work
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

My complete code on github

You can't aggregate on something that isn't a field: subtotal is not a field.

i resolved
https://github.com/rg3915/vendas/commit/cb8230ee52f10d917305f87f33bc749fd120afbb
Thanks.
def get_total(self):
        s = self.sales_det.aggregate(
            subtotal_sum=models.Sum('subtotal')).get('subtotal_sum') or 0
        return s


You need to get subtotal in your view code, then pass it to the template as a context variable

Show me how to do this please.
