python – 在棉花糖中循环导入

我有两个彼此相关的对象.我希望能够通过浏览相关属性来访问另一个对象.

例如. A.b_relationship.obj.some_property

如何在不创建循环导入的情况下执行此操作?

# lib.py
class Relationship(object):

    def __init__(self, obj):
        self.obj = obj


# a.py
class A(object):
    b_relationship = Relationship(B)

# b.py
class B(object):
    a_relationship = Relationship(A)

为清楚起见,我添加了这个额外的例子.显然,SQLAlchemy使用backref属性解决了这个问题.我不确定在不破坏它的工作方式的情况下将这种东西应用到棉花糖中是多么可行.也许我需要改变我的心态?

from marshmallow import Schema
from marshmallow.fields import String

from project.database import db


class PersonModel(db.Model):
    name = db.Column(db.String)


class PetModel(db.Model):
    name = db.Column(db.String)
    owner = db.relationship('PersonModel', backref='pets')


class PersonSchema(Schema):
    name = fields.String(init_arg='some value')
    pets = fields.Relationship(related_schema=PetSchema)


class PetSchema(Schema):
    name = fields.String()
    owner = fields.Relationship(related_schema=PersonSchema)

最佳答案 从这里:

http://marshmallow.readthedocs.org/en/latest/nesting.html#two-way-nesting

查看字符串如何用于该类; AuthorSchema引用’BookSchema’:

class AuthorSchema(Schema):
    # Make sure to use the 'only' or 'exclude' params
    # to avoid infinite recursion
    books = fields.Nested('BookSchema', many=True, exclude=('author', ))
    class Meta:
        fields = ('id', 'name', 'books')

class BookSchema(Schema):
    author = fields.Nested(AuthorSchema, only=('id', 'name'))
    class Meta:
        fields = ('id', 'title', 'author')

我假设在你的情况下,你想用many = False做同样的事情.我从未使用过棉花糖,但在Django中,它类似,我们使用类似“my_app.MyClass”的类路径而不是MyClass来避免循环导入.

点赞