Advertisement
Denjamin

models.py

May 9th, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date, Float
  2. from sqlalchemy.orm import declarative_base
  3. from sqlalchemy.orm import relationship
  4.  
  5. Base = declarative_base()
  6.  
  7.  
  8. # Модельки
  9. class Publisher(Base):
  10.     __tablename__ = 'publisher'
  11.     id = Column(Integer, primary_key=True)
  12.     name = Column(String)
  13.  
  14.  
  15. # Книжки
  16. class Book(Base):
  17.     __tablename__ = 'book'
  18.     id = Column(Integer, primary_key=True)
  19.     title = Column(String)
  20.     id_publisher = Column(Integer, ForeignKey('publisher.id'))
  21.  
  22.     publisher = relationship("Publisher", back_populates="books")
  23.  
  24.  
  25. # Книжки в магазинах
  26. class Stock(Base):
  27.     __tablename__ = 'stock'
  28.     id = Column(Integer, primary_key=True)
  29.     id_book = Column(Integer, ForeignKey('book.id'))
  30.     id_shop = Column(Integer, ForeignKey('shop.id'))
  31.     count = Column(Integer)
  32.  
  33.     book = relationship("Book", back_populates="stocks")
  34.     shop = relationship("Shop", back_populates="stocks")
  35.  
  36.  
  37. # Магазин
  38. class Shop(Base):
  39.     __tablename__ = 'shop'
  40.     id = Column(Integer, primary_key=True)
  41.     name = Column(String)
  42.  
  43.  
  44. # Продажи
  45. class Sale(Base):
  46.     __tablename__ = 'sale'
  47.     id = Column(Integer, primary_key=True)
  48.     price = Column(Float)
  49.     date_sale = Column(Date)
  50.     id_stock = Column(Integer, ForeignKey('stock.id'))
  51.     count = Column(Integer)
  52.  
  53.     stock = relationship("Stock", back_populates="sales")
  54.  
  55.  
  56. # Настройка обратных связей
  57. Publisher.books = relationship("Book", order_by=Book.id, back_populates="publisher")
  58. Book.stocks = relationship("Stock", order_by=Stock.id, back_populates="book")
  59. Shop.stocks = relationship("Stock", order_by=Stock.id, back_populates="shop")
  60. Stock.sales = relationship("Sale", order_by=Sale.id, back_populates="stock")
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement