Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add filter and search in Flask-admin for models with multiple foreignkey to same model

Is there a way to add filter and search support in flask-admin for model that has 2 foreignkeys to the same model? An example sqlalchemy model is below - two of the fields are foreign keys to the same User model.

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])

If I add 'to_user.id' to column_filters as you do for normal field, I get the following error because flask-admin doesn't know which fk fields to join User table on.

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.

like image 304
kefeizhou Avatar asked Sep 12 '25 22:09

kefeizhou


1 Answers

This issue has been addressed and fixed in Flask-Admin 1.2.0, please Update to 1.2.0 and use string to specify the path: 'rel1.something'.

References:

  • https://github.com/flask-admin/flask-admin/issues/846
  • https://github.com/flask-admin/flask-admin/issues/909
  • https://github.com/flask-admin/flask-admin/commit/db3ee4b01944359f9839c0e3d99fdba640d4d25d
like image 198
Lawrence Liu Avatar answered Sep 15 '25 12:09

Lawrence Liu