1

我使用 SQLAlchemy 将这些类作为我的模型。我已经成功地让棉花糖对我的用户对象进行编码,但是它不会对嵌套的链接对象进行编码。我的 SQLAlchemy 查询正在对 fk 上的链接表进行连接,它工作正常。我无法弄清楚我的 NestedSchema 有什么问题以及为什么它不会编码!

class User(Base):
    __tablename__ = 'user'

    id = Column('id', Integer, primary_key=True)
    username = Column('username', String(255), unique=True)
    link = relationship("Link", backref='user', lazy='joined')


class Link(Base):
    __tablename__ = 'link'

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(255))
    user_id = Column('user_id', Integer, ForeignKey("user.id"), nullable=True)

class LinkSchema(Schema):
    name = fields.Str()
    user = fields.Nested('UserSchema')


class UserSchema(Schema):
    username = fields.Str()
    links = fields.Nested('LinkSchema')

我有一个查询我的数据库的函数,看起来像这样。这将正确返回用户和链接。

def get_user(user_id):
    session = get_session()
    try:
       user = session.query(User).filter(User.id == user_id)
    except exc.SQLAlchemyError:
       return False
   return user

在我的烧瓶路线中,这就是我正在执行的。我能够正确取回我的用户信息,但是 Marshmallow 没有对链接部分进行编码。我知道它在那里是因为打印了 link.name[0]。我已经多次查看文档,根本无法弄清楚出了什么问题。任何提示将非常感谢。

@app.route('/api/user_info/)
def get_user_info():
    user = get_user(user_id)
    for u in user:
        print (u.link[0].name) #this prints the link name so I know its there
    schema = UserSchema(strict=True, many=True)
    result = schema.dumps(user)
    pprint(result.data, indent=2)
    return result.data

这是返回的 json。没有链接!想不通为什么。为简洁起见,我省略了很多列。

[{"username": "erick", "role": 1}]
4

1 回答 1

1

经过数小时的沮丧后,我需要在嵌套的 UserSchema 中将 'links' 设为 'link' 和 many=True。

于 2017-11-21T04:10:31.327 回答