【发布时间】: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