[英]Why I need both relationship and foreign key for Many to One relationship?
在SQLAlchemy for Many to One關系的文檔中,它顯示了以下示例:
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'))
child = relationship("Child")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
許多父母為一個孩子。 然后,如果我們創建一個Parent
,我們需要填充child_id
和child
,這看起來有點多余? 這是強制性的,還是每件事的目的是什么?
child = Child()
Parent(child_id=child, child=child)
另外,在Flask-SQLAlchemy中,有一個簡單關系的例子 ,它創建一個這樣的帖子:
Post(title='Hello Python!', body='Python is pretty cool', category=py)
沒有提供category_id
。 如果我復制該場景,則category_id
值為None
。
為了創建像Parent(child=child)
這樣的新對象,是否足以添加foreign_keys=[child_id]
或者它是否具有進一步的含義?
這不是強制性的; 你不需要填充兩者。 將外鍵設置為相關實例可能是等待顯示自身的錯誤。 你唯一需要做的就是
child = Child()
parent = Parent(child=child)
在此parent.child_id
為None
,它們代表ORM的對象部分就好了。 parent.child
是對創建的child
的引用。 除了Python對象ID之外,它們沒有被持久化到數據庫並且沒有標識。 只有當您將它們添加到Session
並將更改刷新到數據庫時,它們才會收到標識,因為它們使用生成的代理鍵。 這是從對象世界到關系世界的映射發生的地方。 SQLAlchemy自動填充parent.child_id
,以便它們的關系也記錄在數據庫中(請注意,這不是關系模型中的“關系”)。
回到示例,添加一些打印有助於跟蹤發生的情況以及何時:
child = Child()
parent = Parent(child=child)
print(parent.child_id) # None
session.add(parent)
session.flush() # Send changes held in session to DB
print(parent.child_id) # The ID assigned to child
您也可以逆轉這種情況:您可能擁有現有Child
的ID,但不具有實際對象的ID。 在這種情況下,您可以自己分配child_id
。
因此,要回答標題:您不需要ORM relationship
以獲得數據庫外鍵關系,但您可以使用它將數據庫關系映射到對象世界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.