[英]Flask-SQLAlchemy how to store list of ForeignKey Objects
我正在創建一個應用程序,它將收集許多不同“類型”項目的要求,但無法弄清楚如何構建 Flask-SQLAlchemy ORM Model 關系。
我有以下課程:
ItemSize - 一個“類型”,比如 T 恤尺寸。
class ItemSize(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
date_created = db.Column(db.Date(), default=datetime.now())
height = db.Column(db.Integer, nullable=True)
depth = db.Column(db.Integer, nullable=True)
width = db.Column(db.Integer, nullable=True)
ItemSet - 特定 ItemSize 的集合,存儲與 ItemSize 和 Count 的關系。 (例如,ItemSize:'A',計數:2)
class ItemSet(db.Model):
id = db.Column(db.Integer, primary_key=True)
size = db.Column(db.Integer, db.ForeignKey('itemsizes.id'), nullable=True)
count = db.Column(db.Integer, nullable=False)
要求 - 許多 ItemSet 的集合。 (例如,ItemSets [1, 2, 3, 4, 5])
class Specification(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
comments = db.Column(db.String(255), nullable=True)
# THIS IS THE BIT I AM UNSURE OF
# Need this to a collection of Many ItemSets
# Will the below work?
requirements = db.relationship('ItemSet', uselist=True, backref='itemsets')
以上在嘗試創建任何對象時給了我以下錯誤:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Specification->specifications'. Original exception was: Could not determine join condition between parent/child tables on relationship Specification.requirements - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
有誰知道如何實現這種關系?
Specification.requirements -> [Array of ItemSets]
任何指針都非常感謝。
您需要修改這兩個類:
class Specification(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
comments = db.Column(db.String(255), nullable=True)
# THIS IS THE BIT I AM UNSURE OF
# Need this to a collection of Many ItemSets
# Will the below work?
requirements = relationship("ItemSet", back_populates="spec")
class ItemSet(db.Model):
id = db.Column(db.Integer, primary_key=True)
size = db.Column(db.Integer, db.ForeignKey('itemsizes.id'), nullable=True)
count = db.Column(db.Integer, nullable=False)
spec_id = Column(db.Integer, ForeignKey('spec.id'))
spec = relationship("Specification", back_populates="requirements")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.