如何根据多个属性检查在duplicity上插入行?

时间:2016-04-04 15:58:18

标签: python sql database sqlalchemy

我在SQLAlchemy工作。是否可以设置两行的equality,因此如果要插入行并且已存在具有相同2列的行,则可以说' creation_date'和' destination_from',那么第二行不会被插入?

我不想在这些列上创建PRIMARY KEY

我认为手动检查是否已存在包含这些列的行是无效的。

# -*- coding: utf-8 -*-
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
import datetime

engine = create_engine('sqlite:///db.db', echo=False)
Base = declarative_base()

s = sqlalchemy.orm.Session(engine)

class Flight(Base):
    __tablename__ = 'flights'
    id = Column(sqlalchemy.Integer, primary_key=True)
    destination_from = Column(sqlalchemy.String)
    destination_to = Column(sqlalchemy.String)
    creation_date = Column(sqlalchemy.Date)
    start_date = Column(sqlalchemy.Date)
    return_date = Column(sqlalchemy.Date)
    price = Column(sqlalchemy.Float)


Base.metadata.create_all(engine)

def insert_into_flights(**kwargs):
    s.add(Flight(**kwargs))
    s.commit()

1 个答案:

答案 0 :(得分:2)

您不想创建PRIMARY KEY,但无法创建UNIQUE CONSTRAINT

UniqueConstraint('creation_date', 'destination_from')