开发者

Pylons: how to declarative with reflection model definition

Good day!

I'm learning Pylons web framework to create web UI for my database. Currently I'm exploring ways to declare my model. The most sexy way seems to be declarative with reflection. Can I use it with Pylons? (Because model/init.py states that I need to define reflection related staff inside init_m开发者_如何学Codel)

Thanks!


See SQLAlchemy declarative syntax with autoload (reflection) in Pylons for a recent answer in Pylons 1.0:

The solution is to declare the model objects outside the model/__init__.py. I created a new file in the model module, e.g. objects.py. I then declared all my model objects (like Event) in this file. Then, I can import my models like this:

from PRJ.model.objects import Event

Furthermore, to avoid specifying autoload-with for each table, I added this line at the end of init_model():

Base.metadata.bind = engine

This way I can declare my model objects with no boilerplate code, like this:

class Event(Base):
    __tablename__ = 'events'
    __table_args__ = {'schema': 'events', 'autoload': True}

    event_identifiers = relationship(EventIdentifier)

    def __repr__(self):
        return "<Event(%s)>" % self.id


Are you using Pylons version 0.9.7? Pylons allrady stable at 1.0 version.

You can use declarative with reflection direct in model/init.py outside of init_model function. Or you can separate model definitions in any other modules or packages.

model/schema.py

from YOURAPP.model.meta import Base        # for declaration you models and reflection
from YOURAPP.model.meta import Session     # for using sa session object

class Category(Base):
    __tablename__ = 'category'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(70), index=True, unique=True)


    def __unicode__(self):
        return self.name


class Attribute(Base):
     __tablename__ = 'attribute'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(70), index=True)


    #Relation
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relation(Category, backref=backref('attributes',
                    order_by=(name,))


    def __unicode__(self):
        return self.name

in model/init.py

from YOURAPP.model.schema import Category, Attribute
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜