SQLAlchemy重复条目

SQLAlchemy重复条目

我有以下代码:

    purchased_offer = session.query(PurchasedOffer).filter_by(purchased_offer_id=purchased_offer_id).first()
    used_offer = UsedOffer(purchased_offer)
    session.add(used_offer)
    session.delete(purchased_offer)


我只是将purchased_offer传送到used_offer表,然后删除purchased_offer

两个表UsedOfferPurchasedOffer仅在名称上有所不同,并且在内容方面相同。

class UsedOffer(Base):
__tablename__ = 'used_offer'

used_offer_id = Column(Integer, primary_key=True)
user_id = Column(ForeignKey(u'user.user_id'), nullable=False, index=True)
venue_id = Column(ForeignKey(u'venue.venue_id'), nullable=False, index=True)
offer_message = Column(String(1024), nullable=False)

user = relationship(u'User')
venue = relationship(u'Venue')

def __init__(self, purchased_offer):
    self.user_id = purchased_offer.user_id
    self.venue_id = purchased_offer.venue_id
    self.offer_message = purchased_offer.offer_message

class PurchasedOffer(Base):
    __tablename__ = 'purchased_offer'

    purchased_offer_id = Column(Integer, primary_key=True)
    user_id = Column(ForeignKey(u'user.user_id'), nullable=False, index=True)
    venue_id = Column(ForeignKey(u'venue.venue_id'), nullable=False, index=True)
    offer_message = Column(String(1024), nullable=False)

    user = relationship(u'User')
    venue = relationship(u'Venue')

    def __init__(self, user_id = None, venue_id = None, offer_message = None):
        self.user_id = user_id
        self.venue_id = venue_id
        self.offer_message = offer_message


我的问题是,当我将used_offer添加到database时,used_offer_id始终设置为0,因此当我在2nd时间中执行此过程时,会得到duplicate error

任何人对为什么会发生这种情况有任何想法?

最佳答案

您必须为每个used_offer_id设置唯一值(不应始终设置为0),因为您已将其声明为主键。

关于python - SQLAlchemy重复条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30588995/

10-13 00:58