【发布时间】:2014-03-09 12:26:11
【问题描述】:
从下面的代码中,我定义了这样的关系:
UnitTypeRowModel (self-referencing but only one in the doc)
-- PlanPmDefinition (definition in the json doc)
-- PlanPmValues (value in the json doc)
如果我在数据库表中只有一个plan_ou,则当前结果为json:
[{
"children": [],
"parent_id": 1,
"id": 4
}, {
"children": [],
"parent_id": 2,
"plan_pm_id": 2,
"id": 5
"definition": {
"id": 2,
"tag": 0,
"value": {
"plan_pm_id": 2,
"tag": 0,
"plan_ou": 1
}
}
}]
代码:
class PlanPmValues(Base):
__tablename__ = 'plan_pm_municipal_values'
plan_pm_id = Column(Integer, primary_key=True)
tag = Column(Integer, primary_key=True)
plan_ou = Column(Integer) # Filter on this
...
class PlanPmDefinition(Base):
__tablename__ = 'plan_pm_municipal_definition'
id = Column(Integer, primary_key=True)
tag = Column(Integer, primary_key=True) -- always 0
value = relationship(PlanPmValues,
primaryjoin='and_(PlanPmDefinition.id==PlanPmValues.plan_pm_id, ' +
'PlanPmDefinition.tag==PlanPmValues.tag)',
foreign_keys='[PlanPmValues.plan_pm_id, PlanPmValues.tag]',
lazy='joined', uselist=False)
class UnitTypeRowModel(Base):
__tablename__ = 'unit_type_row_model'
__table_args__ = {'schema': base_schema}
id = Column(Integer, primary_key=True)
client_id = Column(Integer, ForeignKey(base_schema + '.client.id'))
parent_id = Column(Integer, ForeignKey(base_schema + '.unit_type_row_model.id'), nullable=True)
plan_pm_id = Column(Integer, nullable=True)
children = relationship(
'UnitTypeRowModel',
lazy='joined',
join_depth=2,
order_by="UnitTypeRowModel.sort_order")
definition = relationship(
'PlanPmDefinition',
primaryjoin='and_(PlanPmDefinition.id==UnitTypeRowModel.plan_pm_id, ' +
'PlanPmDefinition.tag==0)',
foreign_keys='[UnitTypeRowModel.plan_pm_id]',
lazy='joined',
uselist=False)
@staticmethod
def get_for_unit(client_id, unit_id):
db_session = DatabaseEngine.get_session()
row_models = db_session.query(UnitTypeRowModel).\
filter(UnitTypeRowModel.client_id == client_id).\
order_by(UnitTypeRowModel.sort_order)
json = util.Serialize.serialize_to_json(row_models)
db_session.close()
return json
如何在方法UnitTypeRowModel.get_for_unit 中从PlanPmValues 类中过滤plan_ou?
【问题讨论】:
标签: python filter sqlalchemy relationship