Col*_*len 3 python python-import importerror marshmallow
我有两个彼此相关的对象.我希望能够通过浏览相关属性来访问另一个对象.
例如 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)
Run Code Online (Sandbox Code Playgroud)
为清楚起见,我添加了这个额外的例子.显然,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)
Run Code Online (Sandbox Code Playgroud)
从这里: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')
Run Code Online (Sandbox Code Playgroud)
我假设在你的情况下,你想做同样的事情many=False.我从来没有使用过棉花糖,但在Django中,它类似,我们使用类路径"my_app.MyClass"而不是MyClass避免循环导入.
| 归档时间: |
|
| 查看次数: |
901 次 |
| 最近记录: |