简体   繁体   中英

PostgreSQL/Python: insert new row only if doesn't exists already

My table:

class api(Base):
    __tablename__ = "api"

    id = Column(Integer, primary_key=True)
    date = Column(DateTime, nullable=False)
    gender = Column(String)
    age = Column(String)
    value = Column(Integer)

Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

When I send an api query with dates which overlaps with previous queries duplicate rows are created. How can I avoid that? I can delete duplicates but is there a more efficient way to avoid inserting them in the first place?

您可以创建一个数据库约束 ,该约束禁止重复的条目并处理代码中的错误。

It looks like you are using SQLAlchemy ORM. You can add unique=True to a single column to create constraint on your table. For example:

class API(Base):
    ...
    date = Column(DateTime, nullable=False, unique=True)

You can also create unique constraint on multiple columns by passing UniqueConstraint to __table_args__ . For example:

class API(Base):
    __table_args__ = (
        UniqueConstraint('date', 'gender'),
    )

It is still recommended that you should check the existence before you inserting the new record into the database, since a violation of database constraint will normally be logged in the database log file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM