#Code redundancy

1 messages · Page 1 of 1 (latest)

carmine ruin
#
StockSA = (
    StocksRegisterComposition.objects.filter(
        CDU_WineRegister=Registo, TipoArtDesc="Eng. Semiacabado", Liters__gt=0
    )
    .values("Item", "Description", "CDU_WineRegister", "CDU_Cabaz")
    .order_by("Item")
    .annotate(Sum("BottlesTotal"), Sum("Liters"))
)
context["StockSA"] = StockSA

StockSATotal = StockSA.aggregate(
    Sum("BottlesTotal"),
    total=Coalesce(Sum("Liters"), 0, output_field=FloatField()),
)["total"]
context["StockSATotal"] = StockSATotal

I'd like to know if StockSA.Liters__sum is the same as StockSATotal.total

prime haven
#

No it's not. Liters__sum will be on the "GROUP BY" level (in this case whatever you have in values) whereas the total version will be on the entire queryset level, as in, the sum of Liters__sum per group.

#

So you will end up with:

<StockSA QuerySet [
    {'Liters__sum': 10, ...},
    {'Liters__sum': 20, ...},
    {'Liters__sum': N, ...}
]>

versus

{'total': 10+20+N }
#

As in, the first will yield an sql statement like:

SELECT SUM("Liters") as Liters__sum
FROM app_stocksregistercomposition
GROUP BY "Item", "Description" ...

and the second will yield an sql statement like:

SELECT SUM("col") as total
FROM (
    SELECT col
    FROM app_stocksregistercomposition
    GROUP BY "Item", "Description", ..
)