2

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_model)

Thanks!

Zaar Hai
  • 9,152
  • 8
  • 37
  • 45

2 Answers2

2

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
Community
  • 1
  • 1
Marmaduke
  • 541
  • 3
  • 8
0

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
estin
  • 3,051
  • 1
  • 24
  • 31
  • 0.9.7 because debian comes with 0.9.7 currently, and pylons book references 0.9.7 as well. In your example, you do not use *reflection* in any place. Please explain. – Zaar Hai Jun 20 '10 at 07:08