R
R
RainbowPesimist2020-11-05 11:05:18
Django
RainbowPesimist, 2020-11-05 11:05:18

How to merge two queryset queries on the same field?

Here is my request code

by_day = transactions_list.annotate(day=TruncDay('date_transaction',output_field=DateField())).filter(type=Transaction.Type.SALE)
date_sales_total = by_day.values('date_transaction',"score_id").annotate(total_sales=Sum('total'))
by_day = transactions_list.annotate(
       day=TruncDay('date_transaction', output_field=DateField())).filter(type=Transaction.Type.EXPENSE)
date_expenses_total = by_day.values('date_transaction',"score_id").annotate(total_expenses=Sum('total'))

What does the result of two queries look like?
date_sales_total >> <QuerySet [{'date_transaction': datetime.date(2019, 2, 10), 'score_id': 1, 'total_sales': 2000000.0}, {'date_transaction': datetime.date(2019, 11, 3), 'score_id': 1, 'total_sales': 1245432.0}]>
date_expenses_total >> <QuerySet [{'date_transaction': datetime.date(2019, 2, 10), 'score_id': 1, 'total_expenses': 500000.0}, {'date_transaction': datetime.date(2019, 12, 10), 'score_id': 1, 'total_expenses': 1214.0}]>

What is expected to be received
<QuerySet [{'date_transaction': datetime.date(2019, 2, 10), 'score_id': 1, 'total_expenses': 500000.0, 'total_sales': 2000000.0}, {'date_transaction': datetime.date(2019, 11, 3), 'score_id': 1, 'total_sales': 1245432.0},{'date_transaction': datetime.date(2019, 12, 10), 'score_id': 1, 'total_expenses': 1214.0}]>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RainbowPesimist, 2020-11-05
@RainbowPesimist

If anyone needs it, there was such a solution

date_total = by_day.values('date_transaction', "score_id").\
        annotate(total_sales=Sum('total', filter=Q(type=Transaction.Type.SALE)),
                 total_expenses=Sum('total', filter=Q(type=Transaction.Type.EXPENSE)))

S
soremix, 2020-11-05
@soremix

QuerySet.union

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question