簡體   English   中英

棉花糖中的循環導入

[英]Circular import in 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)

為了清楚起見,我添加了這個額外的例子。 顯然 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來避免循環導入。

您可以實現一個RelationshipManager (又名注冊表),所有可以成為關系一部分的類都必須向其注冊。

Relationship初始值設定項可以采用與其相關的類的名稱,而不是實際的類對象。

最后,關系類本身可以從初始化時(通過管理器)給定的名稱延遲加載與其相關的真實類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM