Suppose i have clients in my model (model Client), and suppose each client has a shopping cart (model Cart). Each cart has many items (model CartItems), then to finish, each item has a relation with one product (model Product).
Now, here goes my problem. I want to have the average of all shopping carts, which is based in the sum of all items of each cart, for each client. So i'll try to demonstrate you with more details below.
Try to imagine the directions of the relations like this: Client->Cart->CartItems<-Product
Simplified description of each model:
Client (
id #pk
)
Cart (
id #pk
client_id #fk that references to Client.id
)
CartItems (
id #pk
cart_id #fk that references to Cart.id
product #fk that references to Product.id
)
ProductId (
id #pk
value # The price of the product
)
In pure SQL i've found the solution, and would be something like this query:
SELECT * FROM Client
INNER JOIN Cart ON Client.id = Cart.client_id
INNER JOIN
(SELECT AVG(c.total) AS average, cart_id FROM
(SELECT SUM(Product.price) AS total, CartItems.cart_id AS cart_id
FROM CartItems
INNER JOIN Product ON CartItems.product = Product.id
GROUP BY CartItems.cart_id) AS c GROUP BY c.cart_id) AS d
ON d.cart_id = Cart.id;
Anyone has any idea about how to convert this query to Django's model's patterns?