Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. from sqlalchemy.ext.declarative import declarative_base
  2. from sqlalchemy import Column, Integer, ForeignKey, String, create_engine
  3. from sqlalchemy.orm import relationship, sessionmaker
  4.  
  5. engine = create_engine("sqlite:///:memory:", echo="debug")
  6. Session = sessionmaker(bind=engine)
  7. BASE = declarative_base()
  8.  
  9. session = Session()
  10.  
  11. class Node(BASE):
  12.     __tablename__ = "nodes"
  13.     id = Column(Integer, primary_key=True)
  14.  
  15. class ZoneNodeAssociation(BASE):
  16.     __tablename__ = "zone_node_association"
  17.     node_id = Column(Integer, ForeignKey('nodes.id'),
  18.                      primary_key=True, nullable=False)
  19.     zone_id = Column(Integer, ForeignKey('zones.id'),
  20.                      primary_key=True, nullable=False)    
  21.  
  22. class Zone(BASE):
  23.     __tablename__ = "zones"
  24.     id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
  25.     name = Column(String(255), unique=True)
  26.     nodes = relationship("Node",
  27.                          secondary="zone_node_association",
  28.                          backref="zones",)
  29.  
  30. BASE.metadata.create_all(engine)
  31.  
  32.  
  33. node = Node()
  34. zone = Zone()
  35. session.add(node)
  36. session.add(zone)
  37. zone.nodes.append(node)
  38. session.flush()
  39.  
  40. zna = ZoneNodeAssociation(zone_id=zone.id, node_id=node.id)
  41. session.add(zna)
  42. session.commit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement