将类继承层次结构映射到CRUD

时间:2014-08-21 17:41:06

标签: python sql orm flask sqlalchemy

我一直试图建立一个有时可能是个人或公司的实体。有一些seriv方式来设计它。我决定继承

class Investor(db.Model, ModelMixin):
  __tablename__ = "investors"
  building_type = db.Column(db.String(32))
  __mapper_args__ = {
    "polymorphic_identity": "investors",
    'polymorphic_on': building_type
  }
  id = db.Column(db.Integer, primary_key=True)
  first_name = db.Column(db.Unicode(32))
  last_name = db.Column(db.Unicode(32))

class IndividualInvestor(Investor, ModelMixin):
  __tablename__ = "individual_investors"
  __mapper_args__ = {
    "polymorphic_identity": "individual_investors",
  }
  id = db.Column(db.Integer, db.ForeignKey('investors.id'), primary_key=True)

class CompanyInvestor(Investor, ModelMixin):
  __tablename__ = "company_investors"
  __mapper_args__ = {
    "polymorphic_identity": "company_investors",
  }
  id = db.Column(db.Integer, db.ForeignKey('investors.id'), primary_key=True)

到目前为止一直很好,但是如何使用ORM进行CRUD操作有一些问题。

用户将条目标记为公司,服务器获取

if "company" == request.args.get("type"):
  investor = IndividualInvestor()
else:
  investor = CompanyInvestor()
update_model(investor, request.json)

简化型号更新

def update_model(model, json):
  for key, value in json.items():
    new_value = value
    current_type = str(model.__table__.c[key].type)  # only current properties 
    if current_type in CONVERT_FROM:
        new_value = CONVERT_FROM[current_type](value)
    setattr(model, key, new_value)

这是正确的做法吗?如何更新模型? model.__table__仅当前模型列(无基列)

0 个答案:

没有答案