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来避免循环导入.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...