0

I am trying to improve my understanding of the Django queryset syntax and am hoping that someone could help me check my understanding.

Could this:

total_packed = (
    PackingRecord.objects.filter(
        product=OuterRef('pk'), fifolink__sold_out=False
    ).values('product')  # Group by product
    .annotate(total=Sum('qty'))  # Sum qty for 'each' product
    .values('total')
    )
total_sold = (
    FifoLink.objects.filter(
        packing_record__product=OuterRef('pk'), sold_out=False
    ).values('packing_record__product')
    .annotate(total=Sum('sale__qty'))
    .values('total')
    )
output = obj_set.annotate(
        sold=Subquery(total_sold[:1]),
        packed=Subquery(total_packed[:1]),
).annotate(
    in_stock=F('packed') - F('sold')
)

be safely reduced to this:

in_stock = (
    FifoLink.objects.filter(
        packing_record__product=OuterRef('pk'), sold_out=False
    ).values('packing_record__product') 
    .annotate(total=Sum(F('sale__qty')-F('packing_record__qty')))
    .values('total')
    )
output = obj_set.annotate(
        in_stock=Subquery(total_sold[:1]),
)

Basically, I am trying to move the math being completed in the outer .annotate() into the queryset itself by using the fk relationship instead of running two separate querysets. I think this is allowed, but I am not sure if I am understanding it correctly.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Adam Starrh
  • 6,428
  • 8
  • 50
  • 89
  • At a first sight without going in depth into your queries; `queryset.values()` returns a dict of the queryset itself. And by adding an arguments `queryset.values(*fields)` it'll return a dict limites to the fields passed in the arguments. See the [documentation](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values) – Chiheb Nexus Dec 26 '18 at 20:48
  • Ok, this pattern was recommended to me in another question. Looks like they were using it to sort? https://stackoverflow.com/questions/53892193/can-we-do-arithmetic-using-django-subqueries/53892291#53892291 – Adam Starrh Dec 27 '18 at 17:07

0 Answers0