Advertisement
viking_unet

SQLAlchemy example many-to-many

Aug 20th, 2020
2,395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.43 KB | None | 0 0
  1. """
  2. Пример работы в SQLAlchemy с двумя таблицами, связанными отношением многие ко многим.
  3. """
  4.  
  5. from sqlalchemy import Column, Integer, String, ForeignKey, create_engine, CheckConstraint
  6. from sqlalchemy.ext.declarative import declarative_base
  7. from sqlalchemy.orm import sessionmaker
  8.  
  9.  
  10. engine = create_engine('postgresql+psycopg2://user:user@127.0.0.1/test')
  11. Session = sessionmaker(bind=engine)
  12.  
  13. Base = declarative_base()
  14.  
  15. class Book(Base):
  16.     __tablename__ = 'books'
  17.     id = Column(Integer, primary_key=True)
  18.     name = Column(String)
  19.     rating = Column(Integer)
  20.     __table_args__ = (CheckConstraint('rating >= 1 and rating <= 5', name='check_rating'), {})
  21.    
  22.     def __init__(self, name, rating):
  23.         self.name = name
  24.         self.rating = rating
  25.        
  26.     def __repr__(self):
  27.         return "<Book(%s, '%s', %s)>" % (self.id, self.name, self.rating)
  28.    
  29. class Author(Base):
  30.     __tablename__ = 'authors'
  31.     id = Column(Integer, primary_key=True)
  32.     name = Column(String)
  33.    
  34.     def __init__(self, name):
  35.         self.name = name
  36.        
  37.     def __repr__(self):
  38.         return "<Author(%s, '%s')>" % (self.id, self.name)
  39.  
  40. class AuthorToBook(Base):
  41.     __tablename__ = 'authors_to_books'
  42.     id = Column(Integer, primary_key=True)
  43.     author_id = Column(Integer, ForeignKey('authors.id'))
  44.     book_id = Column(Integer, ForeignKey('books.id'))
  45.    
  46.     def __init__(self, author, book):
  47.         self.author_id = author
  48.         self.book_id = book
  49.        
  50.     def __repr__(self):
  51.         return "<AuthorToBook(id %s, author %s, book %s)>" % (self.id, self.author_id, self.book_id)
  52.  
  53. Base.metadata.create_all(engine)
  54.  
  55. session = Session()
  56.  
  57. # чистим таблицы перед вставкой (для тестов)
  58. session.query(AuthorToBook).delete()
  59. session.query(Author).delete()
  60. session.query(Book).delete()
  61. session.commit()
  62.  
  63. author1 = Author(name='Александр Сергеевич Пушкин')
  64. author2 = Author(name='Михаил Юрьевич Лермонтов')
  65. session.add_all([author1, author2])
  66.  
  67. session.commit()
  68.  
  69. print(*session.query(Author).all(), '', sep='\n')
  70.  
  71. book1 = Book(name='Сказка о царе Салтане', rating=5)
  72. book2 = Book(name='Озорная классика для взрослых', rating=3)
  73. book3 = Book(name='Герой нашего времени', rating=4)
  74. session.add_all([book1, book2, book3])
  75.  
  76. session.commit()
  77.  
  78. print(*session.query(Book).all(), '', sep='\n')
  79.  
  80. publication1 = AuthorToBook(author=author1.id, book=book1.id)
  81. publication2 = AuthorToBook(author=author1.id, book=book2.id)
  82. publication3 = AuthorToBook(author=author2.id, book=book2.id)
  83. publication4 = AuthorToBook(author=author2.id, book=book3.id)
  84. session.add_all([publication1, publication2, publication3, publication4])
  85.  
  86. session.commit()
  87.  
  88. print(*session.query(AuthorToBook).all(), '', sep='\n')
  89.  
  90. """
  91. <Author(69, 'Александр Сергеевич Пушкин')>
  92. <Author(70, 'Михаил Юрьевич Лермонтов')>
  93.  
  94. <Book(55, 'Сказка о царе Салтане', 5)>
  95. <Book(56, 'Озорная классика для взрослых', 3)>
  96. <Book(57, 'Герой нашего времени', 4)>
  97.  
  98. <AuthorToBook(id 49, author 69, book 55)>
  99. <AuthorToBook(id 50, author 69, book 56)>
  100. <AuthorToBook(id 51, author 70, book 56)>
  101. <AuthorToBook(id 52, author 70, book 57)>
  102. """
  103.  
  104. print('done')
  105.  
  106.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement