SQLAlchemy: foreign key to multiple tables
Although the @property
decorator will work in the application it might be better to use the @hybrid_property
from the sqlalchemy.ext.hybrid
package. In that way you will be able to filter on that property just like any normal attribute.
Your Book class would then look like:
class Book(Model):
__tablename__ = 'book'
title = db.Column(db.String)
american_author_id = db.Column(db.Integer, db.ForeignKey("american_author.id"), nullable=True)
british_author_id = db.Column(db.Integer, db.ForeignKey("british_author.id"), nullable=True)
@hybrid_property
def author_id(self):
return self.american_author_id or self.british_author_id
I think you can't build a relationship with two different tables using the same column.
Try creating two different columns ("american_author_id" and "british_author_id") then make a @property "author" that returns the author that isn't NULL.
This way you can get the author using: mybook.author