SQLAlchemy基本问题 [英] SQLAlchemy Basic Question

查看:82
本文介绍了SQLAlchemy基本问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何具有SQLAlchemy经验的人,我相信这将是基本知识;但是我没有找到有用的文档,我讨厌挠头.

To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.

给出两个类:

class User(Base):
    __tablename__='users'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    ...

class UserPost(Base):
    __tablename__='posts'
    id = Column(Integer, primary_key=True)
    poster = Column(Integer, ForeignKey('users.id'))
    subject = Column(String(32))

我追求的是一种方法:

post = session.query(UserPost).filter_by(subject="foo").one()
print post.poster.name
>>> "John Doe"

我尝试使用relation()属性进行此操作,但是我一直在绕圈走动,并且发现有关联接关系等的错误:S

I was attempting this with a relation() attribute, but I just kept going round in circles with errors regarding relationship of joins and so on :S

我的关系如下:

class UserPost(Base):
    __tablename__='posts'
    id = Column(Integer, primary_key=True)
    poster = Column(Integer, ForeignKey('users.id'))
    subject = Column(String(32))
    poster_user = relation(User, primaryjoin=poster==User.id)

我对SQLAlchemy的巫术是陌生的,所以要小心! :)

I am new to the voodoo of SQLAlchemy so be gentle! :)

在此先感谢大家,如果这变成了RTFM或错误的结束,请提前道歉

Thanks in advance guys, and apologies in advance if this turns into a RTFM or wrong-end-of-stick

推荐答案

我认为您只是向后定义了关系定义.

I think you just have the relation definition backwards.

尝试:

class User(Base):
    __tablename__='users'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    posts = relation("UserPost", backref="poster")

class UserPost(Base):
    __tablename__='posts'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    subject = Column(String(32))

这篇关于SQLAlchemy基本问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆