Created
August 16, 2013 05:11
-
-
Save ianjosephwilson/6247479 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
import sqlalchemy as db | |
from sqlalchemy.orm import relationship | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import scoped_session, sessionmaker | |
from datetime import datetime | |
Base = declarative_base() | |
class User(Base): | |
__tablename__ = 'user' | |
id = db.Column(db.Integer, primary_key=True) | |
username = db.Column(db.String(80), unique=True) | |
password = db.Column(db.String(12), unique=False) | |
all_conversations = relationship('Conversation', | |
primaryjoin='or_(User.id == Conversation.user1_id, User.id == ' \ | |
'Conversation.user2_id)', lazy='dynamic') | |
# Replies where this is this user. | |
replies = relationship("Reply", backref="user", lazy='dynamic') | |
class Conversation(Base): | |
__tablename__ = 'conversation' | |
id = db.Column(db.Integer, primary_key=True) | |
user1_id = db.Column(db.Integer, db.ForeignKey("user.id")) | |
user2_id = db.Column(db.Integer, db.ForeignKey("user.id")) | |
user1 = relationship('User', foreign_keys=[user1_id], | |
backref='conversations_as_user1') | |
user2 = relationship('User', foreign_keys=[user2_id], | |
backref='conversations_as_user2') | |
# Replies to this conversation. | |
replies = relationship("Reply", backref="conversation", lazy='dynamic') | |
class Reply(Base): | |
__tablename__ = 'reply' | |
id = db.Column(db.Integer, primary_key = True) | |
reply = db.Column(db.Text) | |
user_id = db.Column(db.Integer, db.ForeignKey("user.id")) | |
conversation_id = db.Column(db.Integer, db.ForeignKey("conversation.id")) | |
engine = create_engine('sqlite://') | |
Session = scoped_session(sessionmaker(autoflush=False, autocommit=False)) | |
Session.configure(bind=engine) | |
Base.metadata.create_all(engine) | |
user1 = User(username="user1", password="bla") | |
user2 = User(username="user2", password="bla") | |
Session.add(user1) | |
Session.add(user2) | |
print user1.username | |
print user2.username | |
c1 = Conversation(user1=user1, user2=user2) | |
Session.add(c1) | |
r1 = Reply(reply="yo yo", user=user2, conversation=c1) | |
Session.add(r1) | |
Session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment