首页 > 解决方案 > 如何防止重复条目保存在 Sqlalchemy postgresql 表中?

问题描述

我正在开发一个使用 SQLAlchemy 和 PostgresQl 数据库的项目。我正在尝试将条目保存在两个表中。结构和 Bandit_Page。我的问题是,我试图将条目保存到 Bandit_Pages 表中,当我从烧瓶页面添加最后两个数字时,我正在添加其中的最后两个数字,而上面的条目会自动保存。为了让您深入了解,这是我定义类的代码:

class Structure(db.Model):
    __tablename__ = 'structure'

    arm_id = db.Column(db.Integer, primary_key=True, unique=True)
    page_url = db.Column(db.String())

class Bandit_pages(db.Model):
    __tablename__ = 'bandit_pages'
    campaign_id = db.Column(db.String())
    arm_id = db.Column(db.Integer)
    status = db.Column(db.Boolean, default=False)
    __table_args__ = (
        PrimaryKeyConstraint('campaign_id', 'arm_id'),
        {},)

这是自动添加数据的代码。:

def init(self):
    ###code
    self.structure = {0: "xyz.php"}
    try:
        for arm_id in self.structure:
             new_bandit_page = Bandit_pages(campaign_id=arm_id, arm_id=arm_id, status=True)
             new_bandit_page_1 = Bandit_pages(campaign_id=arm_id, arm_id=arm_id+1, status=False)
             db.session.add_all([new_bandit_page, new_bandit_page_1])
             db.session.commit()
    except Exception as e:
           print("exception in BANDPAGEINIT insert", e)
           db.session.rollback()

这就是在 Bandit_pages 表中添加数据的方式:

myproj=# select * from bandit_pages ;
 campaign_id | arm_id | status 
-------------+--------+--------
           0 |      0 | t
           0 |      1 | f
           0 |      0 | t
           0 |      1 | f
    43137797 |      1 | f
    43137797 |      0 | t
(6 rows)

当我想要一个新页面并且campaign_id 0 被复制两次时,我自己添加了最后两个值(4313779)。所以我想要的是这张桌子:

myproj=# select * from bandit_pages ;

 campaign_id | arm_id | status 
-------------+--------+--------
           0 |      0 | t
           0 |      1 | f
    43137797 |      1 | f
    43137797 |      0 | t
(4 rows)

但我得到了复制的条目。因此,我尝试了在我的代码中使用 distinct()、scalar()、first()、limit() 之类的方法,但这样做只是删除了campaign_id = 0 的所有条目,而表中的值为campaign_id = 43137797。我什至尝试使用主键设置campaign_id,但这并没有将任何值保存到表中。如何防止将条目复制到表中?请帮帮我。

标签: pythonpostgresqlsqlalchemy

解决方案


推荐阅读