1

I want sql query to orm

SELECT id, title,
(SELECT SUM(AMOUNT) FROM web_history A WHERE A.car_id = B.id AND type = 3)
FROM web_car B;


histories = History.objects.filter(car=OuterRef('pk'), type=3)
cars = Car.objects.annotate(count=Subquery(histories.annotate(a=Sum('amount'))))

This can not be done by setting the output_field ... I can not solve it even if I apply variously from FloatField to Char through Concat. I leave a comment on whether I can get advice.

1 Answer 1

2

You seem to be overcomplicating things. You just need a query on Car which annotates the related Histories where type=3.

Car.objects.filter(history__type=3).annotate(count=Sum('history__amount'))
Sign up to request clarification or add additional context in comments.

2 Comments

Hm.. How do you access the History table? 'Type' and 'Amount' are the columns of History
You use the double-underscore syntax, see my edit - I was already doing so for type, needed to add it for history as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.