SqlAlchemy - How to define a foreign key column using model class instead of physical table name

后端 未结 1 1967
独厮守ぢ
独厮守ぢ 2020-12-21 13:04

In brief

I want to use model class to define a foreign-key column.

My google search on this topic is not helpful so I asked here.

In full

相关标签:
1条回答
  • 2020-12-21 13:52

    In brief

    • From model other than Author
      author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c.id))

    • From Author model itself i.e. self-referential - just list the column name
      author_id = db.Column(db.Integer, db.ForeignKey(id))

    • CANNOT use string value
      author_id = db.Column(db.Integer, db.ForeignKey('Author.id'))

    Full details

    ForeignKey accepts column as first argument which can be of type Column or string in format schema_name.table_name.column_name or table_name.column_name. Columns that you define in declarative model turn to InstumentedAttribute objects. That is why db.ForeignKey(Author.id) leads to an error. You can access actual column via __table__ attribute of a model:

    author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c['id']))
    

    or

    author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c.id))
    

    If you need to define self-referencing foreign key you can simply pass the name of column. While declaration of a model is not finished yet it still has Column type:

    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey(id))
    

    Note that you CANNOT define foreign key this way:

    author_id = db.Column(db.Integer, db.ForeignKey('Author.id'))
    

    You need to specify physical table name, mapping class name won't work for it.

    0 讨论(0)
提交回复
热议问题