我有两个彼此相关的对象.我希望能够通过浏览相关属性来访问另一个对象.
例如. 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
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来避免循环导入.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。