Skip to main content
 首页 » 编程设计

python之在 Flask-admin 中添加过滤器并在同一模型中搜索具有多个外键的模型

2024年10月25日10Leo_wl

有没有办法在 flask-admin 中为同一模型具有 2 个外键的模型添加过滤器和搜索支持?下面是一个示例 sqlalchemy 模型 - 其中两个字段是同一用户模型的外键。

class Message(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    to_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True, nullable=False) 
    from_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True, nullable=False)     
    subject = db.Column(db.String(512), default="") 
    content = db.Column(db.Text, default="") 
    to_user = relationship("User", foreign_keys=[to_user_id]) 
    from_user = relationship("User", foreign_keys=[from_user_id]) 

如果我像对普通字段一样将“to_user.id”添加到 column_filters,我会收到以下错误,因为 flask-admin 不知道要在哪些 fk 字段上加入 User 表。

InvalidRequestError: Could not find a FROM clause to join from. Tried joining to user, but got: Can't determine join between 'message' and 'user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

请您参考如下方法:

此问题已在 Flask-Admin 1.2.0 中得到解决和修复,请更新到 1.2.0 并使用字符串指定路径:'rel1.something'。

引用资料: