21

嗨,我无法理解如何使用 sqlalchemy 进行外键引用。我在我的数据库中创建了一个新的表客户端:

class Client(DeclarativeBase):

    __tablename__ = 'client'

    id = Column(Integer, primary_key=True)

    user_id = Column(
        Integer,
        ForeignKey('user.id', ondelete='CASCADE'),
        nullable=False,
        index=True,
    )

    orgname = Column(Unicode, nullable=False)

    def __init__(self, **kwargs):
        super(Client, self).__init__(**kwargs)

不是我想做这样的事情

 u = User(user_name=u'dusual')
 session.add(u)
 c = Client(user=u, orgname="dummy_org")
 session.add(c)

但是 sqlalchemy 回喊说:

(k, cls_.name ) ) TypeError: 'user' is an invalid keyword argument for Client

现在,应该允许用户作为关键字参数,这不是很明显吗?我如何确保我的表能够采用用户关键字参数。

4

1 回答 1

50

您需要定义和模型之间的关系:UserClient

from sqlalchemy.orm import relationship

class Client(DeclarativeBase):

    __tablename__ = 'client'

    id = Column(Integer, primary_key=True)

    user_id = Column(
        Integer,
        ForeignKey('user.id', ondelete='CASCADE'),
        nullable=False,
        # no need to add index=True, all FKs have indexes
    )
    user = relationship('User', backref='clients')

    orgname = Column(Unicode, nullable=False)

    # no need to add a constructor 

然后,您可以通过两种方式关联实例UserClient模型 - 或者通过将整数分配给Client.user_id

u = User(user_name=u'dusual')
session.add(u)
session.flush()  # to make sure the id is fetched from the database
c = Client(user_id=u.id, orgname="dummy_org")
session.add(c)

或通过将User实例分配给Client.user.

u = User(user_name=u'dusual')
# no need to flush, no need to add `u` to the session because sqlalchemy becomes aware of the object once we assign it to c.user
c = Client(user=u, orgname="dummy_org")
session.add(c)

实际上,还有第三种方式——因为我们已经配置了backrefon Client.user,SQLAlchemyclients为我们的模型添加了一个类似列表的属性User

u = User(user_name=u'dusual')
u.clients.append(Client(orgname="dummy_org"))
session.add(u)
于 2013-06-26T20:38:10.700 回答