| 1 | from sqlalchemy import create_engine, Column, Integer, String, Float, ForeignKey |
| 2 | from sqlalchemy.orm import relationship, sessionmaker, declarative_base |
| 3 | |
| 4 | # Define the database connection string. Use an in-memory database for testing. |
| 5 | TEST_DB_URL = "sqlite:///:memory:" # This could also be in a config.py |
| 6 | |
| 7 | engine = create_engine(TEST_DB_URL) |
| 8 | |
| 9 | Session = sessionmaker(bind=engine) |
| 10 | session = Session() |
| 11 | |
| 12 | |
| 13 | # Base for declarative models |
| 14 | Base = declarative_base() |
| 15 | |
| 16 | # Define the association table |
| 17 | class UserMovie(Base): |
| 18 | __tablename__ = 'user_movies' |
| 19 | id = Column(Integer, primary_key=True) |
| 20 | user_id = Column('user_id', Integer, ForeignKey('users.id')) |
| 21 | movie_id = Column('movie_id', Integer, ForeignKey('movies.id')) |
| 22 | user_rating = Column('user_rating', Float, default=0.0 ) |
| 23 | user_comment = Column('user_comment', String) |
| 24 | users = relationship("User", back_populates="user_movies", overlaps="users,movies") |
| 25 | movies = relationship("Movie", back_populates="user_movies", overlaps="users,movies") |
| 26 | |
| 27 | def __repr__(self): |
| 28 | return (f"<UserMovie(user_id={self.user_id}, movie_id={self.movie_id}, " |
| 29 | f"user_rating={self.user_rating})>") |
| 30 | |
| 31 | # Define the User model |
| 32 | class User(Base): |
| 33 | __tablename__ = 'users' |
| 34 | id = Column(Integer, primary_key=True) |
| 35 | name = Column(String) |
| 36 | movies = relationship("Movie", secondary="user_movies", |
| 37 | back_populates="users", overlaps="user_movies,movies") |
| 38 | user_movies = relationship("UserMovie", back_populates="users", |
| 39 | overlaps="user_movies,movies") |
| 40 | |
| 41 | def __repr__(self): |
| 42 | return f"<User(name='{self.name}', id={self.id if self.id else 'None'})>" |
| 43 | |
| 44 | |
| 45 | # Define the Movie model |
| 46 | class Movie(Base): |
| 47 | __tablename__ = 'movies' |
| 48 | id = Column(Integer, primary_key=True) |
| 49 | name = Column(String) |
| 50 | director = Column(String) |
| 51 | year = Column(Integer) |
| 52 | poster = Column(String) |
| 53 | rating = Column(Float) |
| 54 | genre = Column(String) |
| 55 | country = Column(String) |
| 56 | plot = Column(String) |
| 57 | users = relationship("User", secondary="user_movies", |
| 58 | back_populates="movies", overlaps="user_movies,users") |
| 59 | user_movies = relationship("UserMovie", back_populates="movies", |
| 60 | overlaps="user_movies,users") |
| 61 | |
| 62 | def __repr__(self): |
| 63 | return f"<Movie(name={self.name}, id={self.id if self.id else 'None'})>" |
| 64 | |
| 65 | |
| 66 | if __name__ == "__main__": |
| 67 | # This block is for creating the tables if you want to do it directly. |
| 68 | Base.metadata.create_all(engine) |
| 69 | print("Tables created!") |