如何使用sqlalchemy创建外键引用

时间:2013-06-26 16:00:47

标签: python sqlalchemy pyramid

您好我无法理解如何使用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 _。名称)) TypeError:'user'是Client

的无效关键字参数

现在不应该明白,应该允许用户作为关键字参数,如何确保我的表能够接受用户关键字参数。

1 个答案:

答案 0 :(得分:24)

您需要在UserClient型号之间定义relationship

来自sqlalchemy.orm导入关系

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)

实际上,还有第三种方式 - 因为我们在backref上配置了Client.user,SQLAlchemy为我们的{{1}添加了类似列表的clients属性模型:

User