SQLAlchemy联接表继承:如何使用LEFT OUTER JOIN进行SELECT查询

时间:2019-06-17 03:02:01

标签: python sqlalchemy

所以我有两个SQLAlchemy类:

class Report(Base):
    """
    Parent class.
    """

    __tablename__ = 'report'

    record_id = Column(Integer, primary_key=True)
    contact = Column(String(30))
    survey_date = Column(DateTime)
    project = Column(String(100))

    __mapper_args__ = {
        'polymorphic_on': project,
    }


class Survey(Report):
    """
    Child class.
    """
    __tablename__ = 'some_project_survey'

    record_id = Column(Integer, ForeignKey('report.record_id'), primary_key=True)
    form_status = Column(String(150))
    form_comment = Column(String(500))

    __mapper_args__ = {'polymorphic_identity': 'some_project'}

在某些条件下,新的“调查”对象可能会将所有字段分配为“无”。因此,表some_project_survey可能包含NULL行(除了record_id之外,所有字段均为NULL)。并且有很多这样的行。在这种情况下,我决定只创建Report对象,而不创建Survey对象。问题是从数据库中选择Survey对象。标准方法使用INNER JOIN,因此不会返回some_project_survey表中没有记录的Report对象。

然后我决定使用with_polymorphic函数:

entity = with_polymorphic(Report, Survey)
pi = Survey.__mapper_args__['polymorphic_identity']
query = self.session.query(entity)
query = query.filter(entity.reply_project == pi)
result = query.all()

它奏效了。但是,如果报表表中存在对象,而some_project_survey表中不存在对象,则此方法将返回具有report_id属性等于None的对象。

在这种情况下是否有选择调查对象的正确方法?

更新:

当前方法:

entity = with_polymorphic(Report, Survey)
pi = Survey.__mapper_args__['polymorphic_identity']
query = self.session.query(entity, Report.record_id)
query = query.filter(entity.reply_project == pi)
result = query.all()
records = []
for row in result:
    row[0].record_id = row[1]
    records.append(row[0])
return records

0 个答案:

没有答案