我有两个彼此相关的对象。我希望能够通过相关属性来访问一个对象。
E.g. 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
以避免循环导入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)