flask-admin not showing foreignkey columns

梦想与她 提交于 2019-12-05 02:38:39

How about if you change the Child class to this:

class Child(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(120))
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
    parent = db.relationship('Parent', backref=db.backref('children', lazy='dynamic'))

I don't know much about this, and I don't know if you need the back reference, but this setup works for me with Flask-Admin.

You likely need to specify some additional options to flask-admin via a subclass:

class ChildView(ModelView):
    column_display_pk = True # optional, but I like to see the IDs in the list
    column_hide_backrefs = False
    column_list = ('id', 'name', 'parent')


admin.add_view(ChildView(Parent, db.session))

Here is an all-inclusive solution that requires no manual maintenance.

from sqlalchemy import inspect

class ChildView(ModelView):
    column_display_pk = True # optional, but I like to see the IDs in the list
    column_hide_backrefs = False
    column_list = [c_attr.key for c_attr in inspect(Child).mapper.column_attrs]


admin.add_view(ChildView(Child, db.session))
Ali

For what it is worth, none of the solutions listed here worked for me. I was facing the issue where foreign keys were not showing up in Flask-Admin.

This is what worked for them to show up:

class CustomModelViewName(ModelView):
    can_delete = True
    column_hide_backrefs = False
    column_list = ["column_name", "column_name", "etc", "etc", "etc"]
    column_searchable_list = ["column_name"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!