无法从具有一对多关系的模型中导入模式

cannot import schema from a model with one to many relationship

我有两个具有一对多关系的模型:

from marshmallow import Schema, fields
from server import db, ma, app
from .category import CategorySchema


class Analysis(db.Model):
  __tablename__ = 'Analysis'
  __table_args__ = {'extend_existing': True}
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(120), index=True, unique=True)
  description = db.Column(db.Text, nullable=False)
  img = db.Column(db.LargeBinary, nullable=True)
  img_mimetype = db.Column(db.Text, nullable=True)
  img_name = db.Column(db.Text, nullable=True)
  category_id = db.Column(db.Integer, db.ForeignKey('Categories.id'), nullable=True)
  category = db.relationship("Category", back_populates="analysis")


class AnalysisSchema(ma.SQLAlchemyAutoSchema):
  class Meta:
    fields = ("id", "name", "description")
  category = fields.Nested(CategorySchema(exclude=['img', 'analysis']))
from marshmallow import Schema, fields

from server import db, ma, app
from sqlalchemy.ext.hybrid import hybrid_property
from .analysis import AnalysisSchema



class Category(db.Model):
    __tablename__ = 'Categories'
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True, unique=True)
    description = db.Column(db.Text, nullable=False)
    img = db.Column(db.LargeBinary, nullable=False)
    img_mimetype = db.Column(db.Text, nullable=False)
    img_name = db.Column(db.Text, nullable=False)
    analysis = db.relationship("Analysis", back_populates="category")

    @property
    def img_url(self):
        return "/categories/" + str(self.id)



class CategorySchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        # model = Category
        fields = ("id", "name", "description", "img", "img_url", "analysis")
    analysis = fields.Nested(AnalysisSchema, many=True)


class CreateCategorySchema(Schema):
    name = fields.Str(required=True)
    description = fields.Str(required=True)


class UpdateCategorySchema(Schema):
    name = fields.Str(required=True)
    description = fields.Str(required=False)
    img = fields.Str(required=False)
    img_name = fields.Str(required=False)
    img_mimetype = fields.Str(required=False)

我不明白为什么会出现此错误:ImportError: cannot import name 'CategorySchema' from 'server.models.category' (/server/server/models/category.py)

Category 模型上的导入效果很好,而 Analysis 中的模型没有。

您可以通过将 class 名称传递给 nested as a string 来避免循环导入 - 这里的问题。例如:

class AnalysisSchema(ma.SQLAlchemyAutoSchema):
  class Meta:
    fields = ("id", "name", "description")
  category = fields.Nested("CategorySchema", exclude=["img", "analysis"])