【问题标题】:How can I get around a UniqueConstraint error when inserting data into postgresql with flask?使用烧瓶将数据插入 postgresql 时,如何解决 UniqueConstraint 错误?
【发布时间】:2021-03-10 22:06:37
【问题描述】:

我有一个模型,我用它使用烧瓶将数据插入到 postgresql 数据库中:

class UserSchema(Schema):
    class Meta:
        ordered = True

    id = fields.Int(dump_only=True)
    username = fields.String(required=True)
    affiliation = fields.String(required=True)
    email = fields.Email(required=True)
    password = fields.Method(required=True, deserialize='load_password')

    created_at = fields.DateTime(dump_only=True)
    updated_at = fields.DateTime(dump_only=True)

问题是,当我将用户添加到与数据库中另一个用户具有相同隶属关系的数据库时,我收到以下错误:

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates 
unique constraint "user_affiliation_key"
DETAIL:  Key (affiliation)=(dev) already exists.

肯定有一种方法可以将重复值插入到 postgresql 中。我尝试对该字段使用 unique=false ,但它不起作用。任何帮助将不胜感激。

【问题讨论】:

  • edit问题显示sqlalchemy模型代码,以及psql中\d <table-name>的输出。

标签: python postgresql flask sqlalchemy


【解决方案1】:

原来我在模型中设置了 Unique = True。 @snqkecharmerb 感谢您指出这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2013-11-22
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多