kefeizhou
kefeizhou

Reputation: 6552

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.

Upvotes: 4

Views: 3424

Answers (1)

Lawrence Liu
Lawrence Liu

Reputation: 489

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:

Upvotes: 4

Related Questions