Note that there are some explanatory texts on larger screens.

plurals
  1. POSQLAlchemy - Mixin vs MetaClass modification
    text
    copied!<p>So say, for example I have two classes:</p> <pre><code>Base = declarative_base() class Vendor(Base): __tablename__ = "vendor" id = Column(Integer, primary_key=True) name = Column(String(45)) def __init__(self, name): self.name = name def __repr__(self): return "&lt;Vendor id=%d&gt;" % self.id class Site(Base): __tablename__ = "site" id = Column(Integer, primary_key=True) vendor_id = Column(Integer, ForeignKey('vendor.id')) vendor = relation(Vendor) def __init__(self, name, code, location): self.name = name def __repr__(self): return "&lt;Site id=%d&gt;" % self.id class SQLSchema: def __init__(self): self.engine = create_engine('...', echo=False) self.metadata = Base.metadata self.session = sessionmaker(bind=self.engine)() self.create() def create(self): self.metadata.create_all(self.engine) </code></pre> <p>I've simplified the class structure, now, using these classes, I can use:</p> <pre><code>sql = sqlschema.SQLSchema() </code></pre> <p>So, at times, I want easy access to a Vendor, which means I can use:</p> <pre><code>v = sql.session.query(self).filter_by(name='test').one() </code></pre> <p>I'd prefer to simplify the access by using akin to (currently my best effort):</p> <pre><code>Vendor.get(sql.session, name='A-01') </code></pre> <p>It struck me, that the <code>get</code> function is pretty generic that I'd want across all my classes that inherit from Base and I looked into the best way of doing this. There are two ways I can think of:</p> <ul> <li>a Mix-in class</li> <li>Modifying the metaclass supplied to declarative_base</li> </ul> <p>Example of the metaclass modification</p> <pre><code>class MyDeclarativeMeta(DeclarativeMeta): def get(self, session, **filterargs): session.query(self).filter_by(**filterargs).one() ## ... Base = declarative_base(metaclass=MyDeclarativeMeta) </code></pre> <p>I'd like to create something with the least surprise possible. What are people's opinions on the options I've presented and is there a better way altogether?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload