35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from sqlalchemy import Column, Integer, ForeignKey, Float
|
|
from sqlalchemy.orm import relationship
|
|
|
|
from app.db.models.base import Base
|
|
|
|
|
|
class Cart(Base):
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
user_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
|
|
|
# Relationships
|
|
user = relationship("User", back_populates="carts")
|
|
items = relationship("CartItem", back_populates="cart", cascade="all, delete-orphan")
|
|
|
|
@property
|
|
def total(self) -> float:
|
|
return sum(item.subtotal for item in self.items)
|
|
|
|
|
|
class CartItem(Base):
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
cart_id = Column(Integer, ForeignKey("cart.id"), nullable=False)
|
|
product_id = Column(Integer, ForeignKey("product.id"), nullable=False)
|
|
user_id = Column(Integer, ForeignKey("user.id"), nullable=False)
|
|
quantity = Column(Integer, nullable=False, default=1)
|
|
unit_price = Column(Float, nullable=False)
|
|
|
|
# Relationships
|
|
cart = relationship("Cart", back_populates="items")
|
|
product = relationship("Product")
|
|
user = relationship("User", back_populates="cart_items")
|
|
|
|
@property
|
|
def subtotal(self) -> float:
|
|
return self.quantity * self.unit_price |