Below there is a pseudo Many-to-Many table structure of say a customer ordering an event. What I would ideally like to be able to achieve is do implicit queries and sets by using the different relationship names.
For example (presume that the init code creates the associated objects)
order=order()
order.events.corporate.name = "Big Corp"
This would set the event.type (enum) to “corporate” and the event.name to “Big Corp”. Similarly.
print session.query(Order).filter(order.events.corporate.name == "Big Corp")
This would only find the event record that had the associated event.type = “corporate”. (Trivial example and not necessary but you get the idea)
Similarly using order.events.personal.name would set/query the corresponding records with event.type = “personal”
Your help in understanding what is the best way of achieving this functionality would be much appreciated.
Base = declarative_base()
class Order(Base):
__tablename__ = 'order'
id = Column(Integer, primary_key=True)
event_id = Column(Integer, ForeignKey('events.id'))
events = relationship("Events")
class Events(Base):
__tablename__ = 'events'
order_id = Column(Integer, ForeignKey('order.id'), primary_key=True)
event_id = Column(Integer, ForeignKey('event.id'), primary_key=True)
corporate = relationship("Event")
personal = relationship("Event")
event = relationship("Event")
class Event(Base):
__tablename__ = 'event'
id = Column(Integer, primary_key=True)
type = Column(Enum('corporate', 'personal', name='enum_ev_type'))
name = Column(String(32))
SQLAlchemy do not understand the case when relationship is used in filter. In your example
order.events.corporate.I’ve got the following exception while trying to do so:
I would suggest to consider using AssociationObject pattern described in SQL Alchemy Relationships documentation page.
So the query would be:
See full example how to define schema and create objects.
Here is the query produced by sqlalchemy:
PS To enhance the association object pattern such that direct access to the EventsAssoc object is optional, SQLAlchemy provides the Association Proxy extension