Using same foreign key in multiple rows of the same table

时间:2017-06-12 16:50:20

标签: python sqlalchemy

So I have been trying to dynamically create tables in a database and assign them values by dumping dictionaries to them (in sqlalchemy) like this:

    tables_holder = Person(**self.list_of_dicts[0])
    self.session.add(tables_holder) 
    Base.metadata.create_all(self.engine)            
    self.session.flush()
    tables = tables_holder
    for dicts in self.list_of_dicts[1:]:
        if not self.engine.dialect.has_table(self.engine, dicts.get('file_name')):
            Table_Class = type('Table_Class', (Base,), self.attribute_dict_list.get(dicts.get('file_name')))
            Base.metadata.create_all(self.engine)
            bm_name = dicts.get('file_name')
            dicts['person'] = tables
            new_bm = Table_Class(**dicts)
            self.session.add(new_bm)
        else:
            Table_Class = type('Table_Class', (Base,), self.attribute_dict_list.get(dicts.get('file_name')))
            bm_name = dicts.get('file_name')
            dicts['person'] = tables
            new_bm = Table_Class(**dicts)
            self.session.add(new_bm)    

    self.session.commit()

I know this looks a little funky, but everything works as it should until assigning the foreign key from the primary key in the tables_holder object. When I output the foreign key id's from a table with 3 entries it prints as follows:

None
None
1

Am I misunderstanding the abilities of a foreign key? Anything helps.

1 个答案:

答案 0 :(得分:0)

所以事实证明我的问题是在对象的初始创建之后在else语句中重新定义Table_Class引起的。我没想到会重置我的外键。