59 lines
2.6 KiB
Python
59 lines
2.6 KiB
Python
from sqlalchemy import Column, Integer, String, Float, Boolean, DateTime, ForeignKey, Table
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import relationship
|
|
from sqlalchemy.sql import func
|
|
from datetime import datetime
|
|
|
|
Base = declarative_base()
|
|
|
|
# Association table for many-to-many relationship between shopping events and groceries
|
|
shopping_event_groceries = Table(
|
|
'shopping_event_groceries',
|
|
Base.metadata,
|
|
Column('id', Integer, primary_key=True, autoincrement=True), # Artificial primary key
|
|
Column('shopping_event_id', Integer, ForeignKey('shopping_events.id'), nullable=False),
|
|
Column('grocery_id', Integer, ForeignKey('groceries.id'), nullable=False),
|
|
Column('amount', Float, nullable=False), # Amount of this grocery bought in this event
|
|
Column('price', Float, nullable=False) # Price of this grocery at the time of this shopping event
|
|
)
|
|
|
|
class Grocery(Base):
|
|
__tablename__ = "groceries"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
name = Column(String, nullable=False, index=True)
|
|
category = Column(String, nullable=False)
|
|
organic = Column(Boolean, default=False)
|
|
weight = Column(Float, nullable=True) # in grams or kg
|
|
weight_unit = Column(String, default="piece") # "g", "kg", "ml", "l", "piece"
|
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
|
|
|
# Relationships
|
|
shopping_events = relationship("ShoppingEvent", secondary=shopping_event_groceries, back_populates="groceries")
|
|
|
|
class Shop(Base):
|
|
__tablename__ = "shops"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
name = Column(String, nullable=False, index=True)
|
|
city = Column(String, nullable=False)
|
|
address = Column(String, nullable=True)
|
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
|
|
|
# Relationships
|
|
shopping_events = relationship("ShoppingEvent", back_populates="shop")
|
|
|
|
class ShoppingEvent(Base):
|
|
__tablename__ = "shopping_events"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
shop_id = Column(Integer, ForeignKey("shops.id"), nullable=False)
|
|
date = Column(DateTime(timezone=True), nullable=False, default=datetime.utcnow)
|
|
total_amount = Column(Float, nullable=True) # Total cost of the shopping event
|
|
notes = Column(String, nullable=True)
|
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
|
|
|
# Relationships
|
|
shop = relationship("Shop", back_populates="shopping_events")
|
|
groceries = relationship("Grocery", secondary=shopping_event_groceries, back_populates="shopping_events") |