Advertisement
Guest User

Untitled

a guest
Mar 1st, 2016
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import relationship
  5.  
  6. engine = create_engine('postgresql://ubuntu:thinkful@localhost:5432/tbay')
  7. Session = sessionmaker(bind=engine)
  8. session = Session()
  9. Base = declarative_base()
  10.  
  11. from datetime import datetime
  12. from sqlalchemy import Table, Column, Integer, String, Float, DateTime, Date, ForeignKey
  13.  
  14. user_item_table = Table('user_item_association', Base.metadata,
  15. Column('user_id', Integer, ForeignKey('users.id')),
  16. Column('item_id', Integer, ForeignKey('items.id'))
  17. )
  18.  
  19. class User(Base):
  20. __tablename__ = "users"
  21.  
  22. id = Column(Integer, primary_key=True)
  23. username = Column(String, nullable=False)
  24. password = Column(String, nullable=False)
  25. sell_items = relationship("Item",backref="user")
  26. bid_items = relationship("Item", secondary="user_item_association", backref="users")
  27.  
  28. bid_id = Column(Integer, ForeignKey('bids.id'))
  29.  
  30. class Item(Base):
  31. __tablename__ = "items"
  32.  
  33. id = Column(Integer, primary_key=True)
  34. name = Column(String, nullable=False)
  35. description = Column(String)
  36. start_time = Column(DateTime, default=datetime.utcnow)
  37. bids = relationship("Bid", backref="item")
  38.  
  39. user_id = Column(Integer, ForeignKey('users.id'),nullable=False)
  40.  
  41. class Bid(Base):
  42. __tablename__ = "bids"
  43.  
  44. id = Column(Integer, primary_key=True)
  45. price = Column(Float, nullable=False)
  46.  
  47. item_id = Column(Integer, ForeignKey('items.id'),nullable=False)
  48. users = relationship("User", backref="bid")
  49.  
  50. Base.metadata.create_all(engine)
  51.  
  52. John = User(username="John",password="Johnpw")
  53. Michael = User(username="Michael",password="Michaelpw")
  54. Amanda = User(username="Amanda",password="Amandapw")
  55.  
  56. Baseball = Item(name="Baseball", user=John)
  57. Guitar = Item(name="Guitar",user=John)
  58.  
  59. Ball_Bid1 = Bid(price=20.50, item=Baseball)
  60. Ball_Bid2 = Bid(price=22.70, item=Baseball)
  61.  
  62. Michael.bid_items = [Baseball]
  63.  
  64. session.add_all([John, Baseball, Guitar, Ball_Bid1, Ball_Bid2])
  65. session.commit()
  66.  
  67. for item in John.sell_items:
  68. print(item.name)
  69.  
  70. for bid in Baseball.bids:
  71. print(bid.price)
  72.  
  73. for item in Michael.bid_items:
  74. print(item.name)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement