Python 嵌套棉花糖字段和Sqlalchemy关系

Python 嵌套棉花糖字段和Sqlalchemy关系,python,sqlalchemy,marshmallow,Python,Sqlalchemy,Marshmallow,在我的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.

在我的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)
当我尝试在FooBar的棉花糖模式中嵌套类Foo或Bar时,我没有得到任何结果(字典中没有任何对类Foo或Bar的引用)


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

好的。。。我会给你解决问题的办法

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)
但是分析你的代码,我认为我们可以让它更像python

如果且仅当关联表中没有额外数据时,我们可以更改某些内容

查看SQLAlchemy文档中的关系,我们可以使用
relationship()
secondary
参数。 我们必须保持您当前的课堂,课堂
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
也使得
Foo.Bar
中有一个
Bar
列表成为可能

现在我们必须配置
BarSchema
FooSchema

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
是为了避免递归问题。

好吧,如果关联表中有额外的数据呢?那么您将使用行为类似于多对一和一对多的关联对象,其中关联对象将是“一”。由于关联对象也是一个模型,所以它可能有自己的模式类。如果您有问题或困难,请创建一个问题,我将尝试用代码采样器帮助您记住在使用关联对象时还有其他策略,例如使用,那么模式类的配置将取决于所采用的策略
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)