hybrid_property -> calculate average order value

Viewed 15

My datamodel looks like this (simplified):

Product
sku | name


Order
id | created_at


OrderItem
id | order_id | quantity | price | product_sku

My goal is to display in the products the average monthly sales of the past x months. I have added a hybrid property to products. I have something like the following, but unfortunately I can't execute that statement, because it's telling me that there is no application found.

This is what I got. I guess I could just calc all of this in code, but that would not be very efficient. Any other ideas?

class Product(db.Model):
  sku = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
  name = db.Column(db.String(240), nullable=False)

  @hybrid_property
  def avg_monthly_sales(self):
      select(func.avg(OrderItem.quantity)).join(Order, Order.key == OrderItem.id).where(self.sku == OrderItem.id)
      return "avg monthly sales"
0 Answers
Related