I am working on e-commerce app's database, I have a One to Many relationship - using SQLAlchemy relationship() - between the Order table(parent) and the OrderItem table(children).
Database:
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
total = db.Column(db.Integer, nullable=False)
submitted_on = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
delivery_charges = db.Column(db.Integer, nullable=False)
sub_total = db.Column(db.Integer, nullable=False) # needs to be calculated automatically
total_quantity = db.Column(db.Integer, nullable=False) # needs to be calculated automatically
order_items = db.relationship('OrderItem', backref='order', lazy=True)
def __init__(self, customer_id, delivery_charges, sub_total, total_quantity):
self.customer_id = customer_id
self.delivery_charges = delivery_charges
self.sub_total = sub_total
self.total_quantity = total_quantity
self.total = delivery_charges + sub_total
class OrderItem(db.Model):
__tablename__ = "order_item"
id = db.Column(db.Integer, primary_key=True)
order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False)
product_size_color_id = db.Column(db.Integer, db.ForeignKey('product_size_color.id'), nullable=False)
sale_id = db.Column(db.Integer, db.ForeignKey('sale.id'), nullable=True, default=None)
selling_price = db.Column(db.Integer, nullable=False) # needs to be calculated automatically
quantity = db.Column(db.Integer, nullable=False)
what I am trying to do is: I want certain columns to be calculated automatically depending on values from other tables as such:
-Order.total_quantity: the sum of each order_item.quantity corresponding to the same Order instance
-Order.sub_total: the sum of each order_item.selling_price corresponding to the same Order instance.
-Order_item.selling_price: ...
I used default to get some columns sat automatically like in Order.submitted_on and used __init__ function in class Order to calculate the Order.total value as answered in this question, However, these two methods only works if the values are withing the class/table itself, my question is: How can I automatically set values for columns depending on other tables' values?!!
I tried the following code on column Order.total_quantity, It filled the column with zeros!
def __init__(self, customer_id, delivery_charges, sub_total):
self.customer_id = customer_id
self.delivery_charges = delivery_charges
self.sub_total = sub_total
order_items = self.order_items
self.total_quantity = sum([i.quantity for i in order_items])
self.total = delivery_charges + sub_total
Is what I am trying to do possible? How?
datetime.datetime.utcnowordatetime.datetime.nowfor your default time, as it won't evaluate until committing changes to the database. If you're using a transaction manager, this won't be a big deal, and it might not be a big deal anyways, but it's something to be aware of.