尝试设置多个关联对象时,backref上的键错误

时间:2015-07-11 21:16:16

标签: python postgresql flask sqlalchemy

我试图使用sqlalchemy设置一个基本的多对多关系,并且无法确定我做错的事情。从本质上讲,我有一个用户表和一个优惠表(基本上就像Groupon一样)。用户可以响应许多优惠,并且可以向许多用户发送优惠。我一直在使用sqlalchemy docs的这一部分,但显然我做错了。
这是我的代码的相关部分:

class Offer(db.Model):
     __tablename__ = 'offers'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    description = Column(String)
    users = association_proxy('user_offers', 'user')

    def __init__(self, title, description):
        self.title = title
        self.description = description

class User(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String, nullable=False)
    last_name = Column(String, nullable=False)
    email = Column(String, index=True, unique=True)

    def __init__(self, first_name, last_name, email):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email.lower()

class UserOfferResponse(db.Model):
    __tablename__ = 'user_offer_responses'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    offer_id = Column(Integer, ForeignKey('offers.id'))
    response = Column(String)
    created_at = Column(DateTime)

    offer = relationship(Offer,
            backref=backref("user_offers",
                            cascade="all, delete-orphan")
        )
    user = relationship("User")

    def __init__(self, offer=None, user=None, response="", created_at=datetime.datetime.now()):
        self.response = response
        self.offer = offer
        self.user = user
        self.created_at = created_at

使用上面的代码,我可以创建一个Offer和一个User,但如果我尝试将两者关联起来(offer.users.append(user)),我会收到以下错误:

File "/Users/scottmorse/.virtualenvs/WhereItsApp/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 224, in __set__
    instance_dict(instance), value, None)
  File "/Users/scottmorse/.virtualenvs/WhereItsApp/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 802, in set
    value = self.fire_replace_event(state, dict_, value, old, initiator)
  File "/Users/scottmorse/.virtualenvs/WhereItsApp/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 824, in fire_replace_event
    self._replace_token or self._init_append_or_replace_token())
  File "/Users/scottmorse/.virtualenvs/WhereItsApp/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 1153, in emit_backref_from_scalar_set_event
    child_impl = child_state.manager[key].impl
KeyError: 'user_offers'

任何帮助都将不胜感激,并感谢您的阅读。

1 个答案:

答案 0 :(得分:4)

在这里找到答案:KeyError when adding objects to SQLAlchemy association object

因为我试图将用户添加到商品列表中,我需要1)确保User是传递给UserOfferResponse构造函数的第一个项目(因为它是assoc_proxy调用它的方式,或者2)向association_proxy添加一个显式的'creator'参数。

我选择了选项2,因为它允许我在“双向”工作。谢谢你的阅读!