2

在我的 sqlalchemy 课程中,我有以下课程:

class FooBar(Model):
    __tablename__ = ‘foobar’
    id = Column('id', Integer, primary_key=True)

    foonr = Column('foonr', Integer, ForeignKey('foo.nr'), nullable=False)
    barnr = Column('barnr', String, ForeignKey('bar.nr'), nullable=False)

class Foo(Model):
    __tablename__ = ‘foo’
    nr = Column('nr', Integer, primary_key=True)
    foo_name = Column(‘name’,String)


class Bar(Model):
   __tablename__ = ‘bar’
   nr = Column('nr', Integer, primary_key=True)
   bar_name = Column(‘name’,String)
   foo_bar = relationship('foobar', uselist=False)

当我尝试将 Foo 或 Bar 类嵌套在 FooBar 的 Marshmallow 模式中时,我没有得到任何结果(字典没有对 Foo 或 Bar 类的任何引用)。

class FooBarSchema(Schema):
   id = fields.Int()
   foo = fields.Nested('FooSchema', many=False)
   bar = fields.Nested('BarSchema', many=False)

如何在 FooBarSchema 的结果中获取 Foo 和 Bar 类?

4

1 回答 1

1

好的...我会给你解决你的问题。

class FooBar(Model):
    __tablename__ = 'foobar'
    id = Column('id', Integer, primary_key=True)
    foonr = Column('foonr', Integer, ForeignKey('foo.nr'), nullable=False)
    barnr = Column('barnr', String, ForeignKey('bar.nr'), nullable=False)
    foo = relationship("Foo", uselist=False)
    bar = relationship("Bar", uselist=False)

class FooBarSchema(Schema):
    id = fields.Int()   
    foo = fields.Nested('FooSchema', many=False)
    bar = fields.Nested('BarSchema', many=False)

但是分析你的代码我认为我们可以让它更 Pythonic。

当且仅当您在关联表中没有额外数据时,我们才能更改一些内容。

查看 SQLAlchemy 文档中的多对多关系,我们可以使用. 我们必须保持你目前的课程和这样的课程:secondaryrelationship()Bar

class Bar(Model):
    __tablename__ = 'bar'
    nr = Column('nr', Integer, primary_key=True)
    bar_name = Column('name',String)
    foos = relationship("Foo", secondary="foobar", backref="bars")

因此,Bar.foos我们有一个Foo对象列表,并且backref也可以BarFoo.bars.

现在我们必须配置BarSchemaFooSchema类。

class FooSchema(Schema):
    nr = fields.Int()   
    foo_name = fields.Str()
    bars = fields.Nested('BarSchema', exclude=('foos',), many=True)

class BarSchema(Schema):
    nr = fields.Int()   
    bar_name = fields.Str()
    foos = fields.Nested('FooSchema', exclude=('bars',), many=True)

exclude是为了避免递归问题。

于 2017-05-22T22:05:03.440 回答