如何防止在Sqlalchemy postgresql表中保存重复条目?

2024-06-16 15:08:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从事一个使用SQLAlchemy和PostgresQl数据库的项目。我试图将条目保存在两个表中。结构和Bandit_页面。我的问题是,我试图将条目保存到Bandit_Pages表中,在该表中,当我从flask页面添加最后两个数字时,最后两个数字由我添加,而上面的条目则自动保存。为了让您有所了解,以下是我定义类的代码:

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)

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

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()等方法,但这样做只是删除了所有活动id为0的条目,留下了活动id为43137797的值。我甚至尝试过用主键设置活动id,但没有将任何值保存到表中。 如何防止将条目复制到表中?请帮帮我


Tags: 代码idtruenewdbstatuspage条目