i have users and entities (many-to-many) , and using sqlalchemy, with this model:
from sqlalchemy import Table, Column, Unicode, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
users_entities = Table('users_entities', Base.metadata,
Column('userID', Integer, ForeignKey('users.id')),
Column('entitieID', Integer, ForeignKey('entities.id'))
)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(Unicode(20))
password = Column(Unicode(101))
entities = relationship("Entities", secondary=users_entities)
def __init__(self, username, password):
self.username = username
self.password = password
class Entities(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
name = Column(Unicode(20))
descr = Column(Unicode(101))
url = Column(Unicode(101))
def __init__(self, name, descr, url):
self.name = name
self.descr = descr
self.url = url
so, when i use:
user = dbsession.query(User).filter_by(id=session["userID"]).first()
entities = user.entities
i get the user with the user data, and the entities(user.entities) with all the user’s entities.
but instead of getting all the entities, now i need to get an entity from the user where the id is = X
something that would work like this:
user.query(Entities).filter_by(id=X)
i can’t find a simple(“best”) way to do this, am i missing something?
You are looking for Dynamic Relationship Loaders, they’re exactly what you want to do, and enable you to write:
By the way, you can write
user = dbsession.query(User).get(session["userID"]). It does the same query, but only if the object is not already in the session cache (plus, it’s shorter).