2

下面是一个伪多对多表结构,假设客户订购了一个活动。我理想地希望能够实现的是通过使用不同的关系名称进行隐式查询和设置。

例如(假设初始化代码创建了关联对象)

order=order()
order.events.corporate.name = "Big Corp"

这会将 event.type(枚举)设置为“corporate”,将 event.name 设置为“Big Corp”。相似地。

print session.query(Order).filter(order.events.corporate.name == "Big Corp")

这只会找到具有关联 event.type = "corporate" 的事件记录。(简单的例子,没有必要,但你明白了)

同样,使用 order.events.personal.name 将设置/查询 event.type = "personal" 的相应记录

非常感谢您帮助理解实现此功能的最佳方式。

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

1 回答 1

3

SQLAlchemy 不理解在过滤器中使用关系的情况。在你的例子order.events.corporate中。

我在尝试这样做时遇到以下异常:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Order.events has an attribute 'corporate'

我建议考虑使用SQL Alchemy 关系文档页面中描述的AssociationObject模式。

所以查询将是:

session.query(Order).filter(and_(EventsAssoc.type=="corporate",Event.name=="Big Corporation"))

查看完整示例如何定义模式和创建对象。

from sqlalchemy import *
from sqlalchemy import create_engine, orm
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship



metadata = MetaData()
Base = declarative_base()
Base.metadata = metadata



class Event(Base):
    __tablename__ = 'event'
    id                  = Column(Integer, Sequence("event_seq"), primary_key=True)
    name                = Column(String(32))
    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)


class EventsAssoc(Base):
    __tablename__ = 'events'
    id                  = Column(Integer, Sequence("events_seq"), primary_key=True)
    left_id = Column(Integer, ForeignKey('order.id'))
    right_id = Column(Integer, ForeignKey('event.id'))

#    order_id            = Column(Integer, ForeignKey('order.id'), primary_key=True)
#    event_id            = Column(Integer, ForeignKey('event.id'), primary_key=True)
    type                 = Column(Enum('corporate', 'personal', name='enum_ev_type'))

    event = relationship(Event, backref="order_assocs")

    def __repr__(self):
        return "%s(events=%r,id=\"%s\")" % (self.__class__.__name__,self.event,self.id)


class Order(Base):
    __tablename__ = 'order'
    id                  = Column(Integer, Sequence("order_seq"), primary_key=True)
    name = Column(String(127))
    events = relationship(EventsAssoc)
    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)


db = create_engine('sqlite:////temp/test_assoc.db',echo=True)



#making sure we are working with a fresh database
metadata.drop_all(db)
metadata.create_all(db)


sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

o = Order(name="order1")
ea_corp = EventsAssoc(type="corporate")
ea_corp.event = Event(name="Big Corporation")

ea_pers = EventsAssoc(type="personal")
ea_pers.event = Event(name="Person")


o.events.append(ea_corp)
o.events.append(ea_pers)
session.add(o)
session.flush()

query = session.query(Order).filter(and_(EventsAssoc.type=="corporate",Event.name=="Big Corporation"))

for order in query.all():
    print order
    print order.events

这是 sqlalchemy 生成的查询:

SELECT "order".id AS order_id, "order".name AS order_name 
FROM "order", events, event 
WHERE events.type = ? AND event.name = ?
('corporate', 'Big Corporation')

PS 为了增强关联对象模式,以便直接访问 EventsAssoc 对象是可选的,SQLAlchemy 提供了关联代理扩展

于 2013-01-16T23:39:00.587 回答