SQLAlchemy和自动脚本:重复的键值违反了唯一约束

时间:2019-04-30 21:41:21

标签: python postgresql sqlalchemy

我使用sqlalchemy作为ORM在python中与Postgresql数据库进行交互。我开发了定义sqlalchemy数据模型的python类。这是我的用例:在一个excel文件中,我为每个数据模型定义了一个包含数据的工作表。在每个工作表中,列对应于变量,行对应于数据。

我编写了一个读取excel文件的python脚本,我在postgresl中为每个工作表的每一行创建行。这部分有效!

MODELS_CONSTRUCTORS = [ # Python Classes defining Sqalalchemy models
    {"User" : User()},
    {"Entity" : Entity()},
    {"BusinessProfile" : BusinessProfile()},
    {"Role" : Role()}
]

CONNECTOR = SqlaConnector()
SESSION = SqlaConnector().session
ENGINE = SqlaConnector().engine

def create_dataset():
    try:

        # Initialize Models
        ###### SECTION THAT WORKS ########
        for model_constructor in MODELS_CONSTRUCTORS:
            for model, constructor in model_constructor.items():
                dataframe = pd.read_excel(xls, model).fillna("") # xls : content of an excel file retrieved with pandas
                for index in dataframe.index:
                    new_instance_of_model = constructor
                    for column in dataframe.columns:
                        setattr(new_instance_of_model, column_name, str(dataframe[column][index]))
                    make_transient(new_instance_of_model) 
                    SESSION.add(new_instance_of_model) # sqlalchemy session
                    SESSION.commit()
        ##########################################
        ###### SECTION THAT DOES NOT WORK ########
        print("test insert user (manual)")
        new_user = User()
        new_user.firstname = "myFirstname2"
        new_user.lastname = "myLastname2"
        new_user.email = "myEmail12@myBox.com"
        new_user.status="Unconfirmed"
        SESSION.add(new_user)
        SESSION.commit()
        print("END")
        ##########################################
    except Exception as ex:
        print("Error in data initialization. %s" % str(ex))
        SESSION.rollback()

但是,当我尝试以常规方式创建新项目(例如新用户)时,出现以下错误:

sqlalchemy.exc.IntegrityError
IntegrityError: (IntegrityError) duplicate key value violates unique constraint "users_key"
DETAIL:  Key (id)=(1) already exists. # id is the primary key in my data model

似乎sqlalchemy无法检测到数据库中已有用户,并尝试将用户插入第一行(因此,详细信息:键(id)=(1)已存在)

如果您能帮助解决此问题,我将非常感谢。

0 个答案:

没有答案