-2

我正在尝试使用带有烧瓶的 sqlalchemy 在 python 上编写一个项目。所以我有部门。

class Departament(db.Model):
    __tablename__ = 'departments'
    id = db.Column(db.Integer(), primary_key=True)
    uuid = db.Column(db.String(36), unique=True)
    title = db.Column(db.String(120), nullable=False)
    employees = db.relationship('Employee', backref='departament', lazy='dynamic')
    average_salary = db.Column(db.Float(16))

    def __init__(self, title, employees=None):
        self.title = title
        self.uuid = str(uuid.uuid4())
        self.average_salary = 0
        self.employees = []
        if employees:
            self.employees=employees
            self.update_avg_salary()

和员工阶层

class Employee(db.Model):
    __tablename__ = 'employees'
    id = db.Column(db.Integer(), primary_key=True)
    uuid = db.Column(db.String(36), unique=True)
    first_name = db.Column(db.String(120), nullable=False)
    last_name = db.Column(db.String(120), nullable=False)
    salary = db.Column(db.Float(16), nullable=False)
    departament_id = db.Column(db.String(36), db.ForeignKey('departments.uuid'))


    def __init__(self, first_name, last_name, salary, departament_uuid=None):
        self.first_name = first_name
        self.last_name = last_name
        self.salary = salary
        self.uuid = str(uuid.uuid4())
        self.departament_id = departament_uuid

所以我不仅要创建一个空部门,然后在那里输入员工,还要创建已经有员工的部门。我正在使用 post 方法。

class DepartamentListApi(Resource):
    departament_schema = DepartamentSchema()

    def get(self, uuid=None):
        if not uuid:
            return self.departament_schema.dump(DepartamentService.fetch_all_departments(db.session), many=True), 200
        departament = DepartamentService.fetch_departament_by_uuid(db.session, uuid)
        return self.departament_schema.dump(departament), 200

    def post(self):
        try:
            departament = self.departament_schema.load(request.json, session=db.session)
        except ValueError as error:
            return {'message': str(error)}, 400
        db.session.add(departament)
        db.session.commit()
        return self.departament_schema.dump(departament), 201

问题是,当我测试创建空部门时,一切都很好,但是当我与员工一起创建部门时,我得到

  File "/somepath/python3.8/site-packages/marshmallow/schema.py", line 896, in _do_load
    raise exc
marshmallow.exceptions.ValidationError: {'employees': {0: {'salary': ['Unknown field.']}}}

这是我的部门课程架构

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from marshmallow_sqlalchemy.fields import Nested

from app.models.models import Departament

class DepartamentSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Departament
        exclude = ['id']
        load_instance = True

    employees = Nested('EmployeeSchema', many=True, exclude=('departament_id', 'salary'))

问题是,我猜,架构不期望 Department 有 2 个参数(“title”和“employees”),但是当只加载“title”时没有任何不好的事情发生。有人知道如何解决吗?我真的很感激。我还将在 GitHub https://github.com/selezenart/department_api上的项目上应用链接

4

0 回答 0