groceries/backend/models.py
2025-05-23 20:44:23 +02:00

58 lines
2.5 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('shopping_event_id', Integer, ForeignKey('shopping_events.id'), primary_key=True),
Column('grocery_id', Integer, ForeignKey('groceries.id'), primary_key=True),
Column('amount', Float, nullable=False) # Amount of this grocery bought in this event
)
class Grocery(Base):
__tablename__ = "groceries"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, index=True)
price = Column(Float, nullable=False)
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")