I have a fairly complex hybrid_property. This is a vendor model, which has multiple skuchannels (products). What it does is: Based on the target_stock_duration (e.g. we want to keep items in stock for 4 months) calculate how many units have to be ordered and how much this would cost. This gives us the potential.
JavaScript
x
33
33
1
class Vendor(db.Model):
2
__tablename__ = "vendor"
3
id = db.Column(db.Integer, primary_key=True)
4
name = db.Column(db.String(150))
5
b2c_price_factor = db.Column(db.Float, nullable=False)
6
skuchannels = db.relationship("SKUChannel", back_populates="vendor")
7
8
@hybrid_property
9
def po_potential(self):
10
"""This is a "virtual" property that will that can be used in the admin view. It calculates
11
the potential value for a comming PO.
12
13
Returns:
14
_type_: _description_
15
"""
16
17
potential = 0
18
for item in self.skuchannels:
19
purchasing_price = item.purchasing_price if item.purchasing_price != None else 0
20
21
target_stock_duration = 4
22
23
try:
24
to_order = item.average_monthly_sales * target_stock_duration - item.stock_level #calculate how many units we have to order
25
if to_order < 0:
26
to_order = 0
27
except TypeError:
28
to_order = 0
29
30
potential = potential + purchasing_price * to_order #calculate how much everything costs
31
32
return potential
33
well this hybrid_property works just fine, but I would very much like to sort this property. with @po_potential.expression -> well I have no clue how to do this, because in my understanding it should return a select object. Is there any other way?
Advertisement
Answer
This should get you started:
JavaScript
1
15
15
1
class Vendor(Base):
2
3
4
@po_potential.expression
5
def po_potential(cls):
6
target_stock_duration = 4
7
return (
8
select(func.sum(
9
func.ISNULL(SKUChannel.purchasing_price, 0) *
10
func.GREATEST(0, SKUChannel.average_monthly_sales * target_stock_duration - SKUChannel.stock_level, 0)
11
))
12
.where(SKUChannel.vendor_id == cls.id)
13
.label('po_potential')
14
)
15