【问题标题】:Can't update SQLAlchemy association table extra columns无法更新 SQLAlchemy 关联表的额外列
【发布时间】:2022-01-27 11:55:53
【问题描述】:

我的模型如下所示:

class Company(DB_BASE):
    __tablename__ = 'Company'

    id = Column(Integer, primary_key=True, index=True)
    ...
    products = relationship('Product', secondary=Company_Products, backref='Company')

class Product(DB_BASE):
    __tablename__ = 'Product'

    id = Column(Integer, primary_key=True, index=True)
    ...
    companies = relationship('Company', secondary=Company_Products, backref='Product')

这是我的关联表

Company_Products = Table(
    'Company_Products',
    DB_BASE.metadata,
    Column('id', Integer, primary_key=True),

    Column('company_id', Integer, ForeignKey('Company.id')),
    Column('product_id', Integer, ForeignKey('Product.id')),

    Column('quantity', Integer, default=0),
    Column('price_per_unit', Integer, default=0),
)

这就是我查询关联表的方式。

company_product = db.query(Company_Products).filter_by(product_id=id, company_id=user.company_id).first()
company_product.quantity = data.data['quantity']
company_product.price = data.data['price']

在创建 Company 和 Product 之间的多对多关系后,我想在此实例中修改关系 extra data、数量和 price_per_unit。查询关联对象后,修改任意属性产生:

AttributeError: can't set attribute 'quantity'

【问题讨论】:

  • 您需要使用和Association Object 来访问/更改额外的列。这对于关联表是不可能的。
  • @rfkortekaas 谢谢你的建议,我会试试这个并更新结果。

标签: python postgresql sqlalchemy fastapi model-associations


【解决方案1】:

跟进我的问题,最终对我有用的解决方案是制作一个新模型并使用它来模拟关联表。

class Company_Products(DB_BASE):
    __tablename__ = 'Company_Products'

    id = Column(Integer, primary_key=True, index=True)
    ...
    quantity = Column(String) # 1 - client, 2 - furnizor
    price_per_unit = Column(String)

    company_id = Column(Integer, ForeignKey('Company.id'))
    company = relationship('Company', back_populates='products', lazy='select')
    product_id = Column(Integer, ForeignKey('Product.id'))
    product = relationship('Product', back_populates='companies', lazy='select')

这绝对不是最好的解决方案,如果我想出其他方法或遇到可能可行的方法,我会编辑它。

【讨论】:

    猜你喜欢
    • 2019-10-16
    • 2016-02-18
    • 2021-12-28
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多