简体   繁体   中英

How to annotate an object with the sum of multilplication of two fields from a related object to a realated object in Django

Given these three classes

    class User(BaseModel):
          name = models.CharField(..)

    class Order(BaseModel):
          user = models.ForeignKey(User,...,related_name='orders')

  class OrderItem(BaseModel):
        order = models.ForeignKey(Order,...,related_name='items'
        quatity = models.IntegerField(default=1)
        price = models.FloatField()


and this is the base class (it is enough to note that it has the created_at field)

    class BaseModel(models.Model):
          createt_at = models.DateTimeField(auto_now_add=True)

Now each User will have multiple Orders and each Order has multiple OrdeItems

I want to annotate the User objects with the total price of the last order.

Take this data for example:

虚拟数据的图像

The User objects should be annotated with the sum of the last order that is for user john with id=1 we should return the sum of order_items (with ids= 3 & 4) since they are related to the order id=2 since it is the latest order.

I hope I have made my self clear. I am new to Django and tried to go over the docs and tried many different things but I keep getting stuck at getting the last order items

Sometimes it's unclear how to make such query in Django ORM. In your case I'd write the query in raw SQL something like:

WITH last_order_for_user AS (
    SELECT id, user_id, MAX(created_at)
    FROM orders
    GROUP BY user_id
) -- last order_id for each user_id
SELECT
    order.user_id, order.id, SUM(item.price)
FROM 
    last_order_for_user order 
LEFT JOIN 
    orderitems item ON order.id=item.order_id
GROUP BY 1,2 -- sum of items for last order, user

And then perform raw SQL django-docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM