Source

CherryPy Recipes / testing / load / myapp / model.py

# -*- coding: utf-8 -*-
import datetime

from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Unicode, Integer, DateTime
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

__all__ = ['Post', 'Comment']

class Post(Base):
    __tablename__ = 'post'
    id = Column(Integer, nullable=False, primary_key=True)
    title = Column(Unicode)
    author = Column(Unicode)
    date = Column(DateTime, default=datetime.datetime.utcnow)
    text = Column(Unicode)
    comments = relationship("Comment", backref="post")

    @staticmethod
    def all_(session):
        return session.query(Post).all()

    @staticmethod
    def get_by_id(session, post_id):
        return session.query(Post).filter(Post.id==post_id).first()
    
class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, nullable=False, primary_key=True)
    author = Column(Unicode)
    date = Column(DateTime, default=datetime.datetime.utcnow)
    text = Column(Unicode)
    post_id = Column(Integer, ForeignKey('post.id'))

    @staticmethod
    def all_(session):
        return session.query(Comment).all()