SQLAlchemy一对多,添加记录

时间:2015-06-17 14:17:35

标签: python sqlalchemy

我有一个关于添加具有一对多关系的记录的查询。

首先,这是我的模型,我与项目/套件/案例/步骤有一个分层的一对多关系。

class Project(Base):
    """Project model for reportr"""
    __tablename__ = 'project'
    id = Column(Integer, primary_key=True)
    name = Column(String(80))

    #  Relationship definitions
    test_suites = relationship("TestSuite", backref="test_suite")

    def __repr__(self):
        return '<Project %r>' % self.name


class TestSuite(Base):
    """Test suite model for reportr"""
    __tablename__ = 'test_suite'
    id = Column(Integer, primary_key=True)
    name = Column(String(80))

    #  Relationship definitions
    project_id = Column(Integer, ForeignKey("project.id"))
    test_cases = relationship("TestCase", backref="test_case")

    def __repr__(self):
        return '<TestSuite %r>' % self.name


class TestCase(Base):
    """Test case model for reportr"""
    __tablename__ = 'test_case'
    id = Column(Integer, primary_key=True)
    name = Column(String(80))

    #  Relationship definitions
    test_suite_id = Column(Integer, ForeignKey("test_suite.id"))
    test_steps = relationship("TestStep", backref="test_step")

    def __repr__(self):
        return '<TestCase %r>' % self.name


class TestStep(Base):
    """Test step model for reportr"""
    __tablename__ = 'test_step'
    id = Column(Integer, primary_key=True)
    name = Column(String(80))

    #  Relationship definitions
    test_case_id = Column(Integer, ForeignKey("test_case.id"))

    def __repr__(self):
        return '<TestCase %r>' % self.name

我有一个接受字典的函数,然后使用SQLAlchemy将信息存储在数据库中。

def save(results):
    """Process the JSON file and save in the database"""
    test_json = json.load(results)
    session = init_session()

    for reportr in test_json['reportr']:
        for project in reportr['project']:
            prj = Project(name=project['name'])
            session.add(prj)
            print prj

            for suite in project['test_suite']:
                sui = TestSuite(name=suite['name'])
                sui.project_id = [prj]
                session.add(sui)
                print sui

                for case in suite['test_case']:
                    cas = TestCase(name=case['name'])
                    cas.test_suite_id = [sui]
                    session.add(cas)
                    print cas

                    for step in case['test_step']:
                        stp = TestStep(name=step['name'])
                        stp.test_case_id = [cas]
                        session.add(stp)
                        print stp

    session.commit()

以TestSuite为例......

目前我收到InterfaceError错误,因为我试图保存一个对象,而不是ID project_id ForeignKey ...如果我将prj.id存储到但是,在我prj.idadd()更改之前,该字段commit()才会填充。

根据我的经验,我不应该做任何事情,直到所有人都处理完毕,但似乎没有它就能建立起关系吗?

我的问题是,我是以错误的方式接近这个吗?如何为父TestSuite和某个孩子Project添加TestCases

谢谢, 约什

1 个答案:

答案 0 :(得分:1)

您可以在session.flush()之后调用add,这样可以让您返回数据库ID:

session.add(sui)
session.flush()
print sui.id

查看transaction management docs了解详情。