简体   繁体   English

Flask中的多对多关系插入记录

[英]Many-to-many relation insert record in Flask

With marshmallow@3.11.1 , Flask@1.1.2 , Flask-SQLAlchemy@2.4.4 and S QLAlchemy@1.3.23 I am trying to store a new data in DB.使用marshmallow@3.11.1Flask@1.1.2Flask-SQLAlchemy@2.4.4和 S QLAlchemy@1.3.23我正在尝试将新数据存储在数据库中。

I do not have any issues creating records without any relations on with one-to-many relations, but I am struggling to create a new record with a many-to-many relations.创建没有任何关系的记录与一对多关系没有任何问题,但我正在努力创建具有多对多关系的新记录。

I have Positions , which may have different Types .我有Positions ,可能有不同的Types To have a many-to-many relation I use an associated table:要建立多对多关系,我使用关联表:

class PositionsModel(db.Model):

  __tablename__ = "positions"

  id = db.Column(db.Integer, primary_key=True)
  position_name = db.Column(db.String(150), nullable=False)

  types_of_work = db.relationship(
    "TypesOfWorkModel",
    secondary=positions_types_of_work,
    lazy="joined",
    backref=db.backref("type_positions", lazy="noload")
  )

def __init__(self, data):
    self.position_name = data.get("position_name")
    self.types_of_work = data.get("types_of_work", [])
  
  def create(self):
    db.session.add(self)
    db.session.commit()

class TypesOfWorkModel(db.Model):

  __tablename__ = "types_of_work"

  id = db.Column(db.Integer, primary_key=True)
  work_type_name = db.Column(db.String(150), nullable=False)


positions_types_of_work = db.Table(
  "positions_types_of_work",
  db.Column("position_id", db.Integer, db.ForeignKey("positions.id"), primary_key=True),
  db.Column("type_of_work_id", db.Integer, 
            db.ForeignKey("types_of_work.id"), primary_key=True)
)

I also have a schema for every other table, which I am using when creating records.我还有一个用于创建记录时使用的所有其他表的模式。 Here is my schema for creating a new Position:这是我创建新 Position 的架构:

class PositionsModelSchemaCreate(Schema):

  id = fields.Int()
  position_name = fields.Str(required=True)
  types_of_work = fields.List(
    fields.Int,
    validate=validate_types_of_work
  )

  @post_load
  def attach_models(self, data, **kwargs):
    # query to get actual model records for "types_of_work"
    return data

So what happens when a request comes to create a new position?那么当请求创建一个新的 position 时会发生什么?

  """
    request data looks like this:
    {
      "position_name": "Test",
      "types_of_work": [1, 2]
    }
  """
  req_data = request.get_json()
  data = positions_schema_create.load(req_data)

This piece of code loads data according to the schema, calls validation functions.这段代码根据模式加载数据,调用验证函数。 In types_of_work case it just checks in the IDs in the request body are the IDs of the existing records in the DB.types_of_work案例中,它只检查请求正文中的 ID 是数据库中现有记录的 ID。

Then it reaches @ post_load decorator, which substitutes the IDs for types_of_work to actual DB records of those types.然后它到达@post_load装饰器,它将types_of_work的ID 替换为这些类型的实际数据库记录。

Eventually, my request data will look like this:最终,我的请求数据将如下所示:

{
  'position_name': 'Pos Name Test',
  'types_of_work': [<TypesOfWork One>, <TypesOfWork Two>]
}

Which I am using for creation:我用于创作:

  position = PositionsModel(data)
  position.create()

And it returns me an error:它返回给我一个错误:

int() argument must be a string, a bytes-like object or a number, not 'TypesOfWorkModel'

I read a few other posts here and here and looks like I am doing everything accordingly, but still have an error.在这里这里阅读了其他一些帖子,看起来我正在做相应的事情,但仍然有错误。

Any advice would be greatly appreciated!任何建议将不胜感激!

Should be应该

position = PositionsModel(**data)
position.create()

if in @post_load return json/dict如果在@post_load 中返回 json/dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM