如何:在flask_admin中显示/编辑association_proxy列

时间:2017-03-09 00:21:21

标签: python-3.x flask associations flask-sqlalchemy flask-admin

是的,我已经看过this question并且已经阅读了尽可能多的flask_admin文档。也就是说,它都非常密集,而我似乎只是一个简单的问题而感到茫然。

代码:

模型(app / models.py)

# Define the models for Paper and Keywords, with intermediary KeywordPaper
# Allows convenience of Paper.keywords += ["keyword"]

class Paper(db.Model):
    # ...
    keywords = association_proxy('paper_keywords', 'keyword',
                                 creator=lambda kw: Keyword(keyword=kw))
    # ...

class KeywordPaper(db.Model):
    # ...
    keyword_id = db.Column(db.Integer,
                           db.ForeignKey('keywords.id'),
                           primary_key=True)
    paper_id = db.Column(db.Integer,
                         db.ForeignKey('papers.id'),
                         primary_key=True)
    keyword = db.relationship(Keyword, lazy='joined')
    paper = db.relationship('Paper',
                            backref=db.backref("paper_keywords",
                                               cascade="all, delete-orphan"))
    # ...

class Keyword(db.Model):
    # ...
    id = db.Column(db.Integer, primary_key=True)
    keyword = db.Column(db.String(50))
    # ...

模型视图(app / auth / model_views.py)

class MainModelView(ModelView):
    # ...
    form_base_class = SecureForm
    # ...

class PaperModelView(MainModelView):
    page_size = 20
    column_list = (
        # ...
        'keywords',
        # ...
    )
    column_searchable_list = (
        # ...
        'keywords',
        # ...
    )
    column_editable_list = (
        # ...
        'keywords',
        # ...
    )
    form_ajax_refs = {
        # ... keywords here?
    }
    # ...

应用/ AUTH / __初始化__。PY

# ...
auth = Blueprint('auth', __name__)
from . import views
auth.model_views = []
# ...
paper_model_view = PaperModelView(Paper, db.session)
auth.model_views += [paper_model_view]
# ...
from . import forms
# ...

应用/ __初始化__。PY

def create_app(config_name):
    # ...
    with app.app_context():
        # ...
        # Initialize auth blueprint
        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)
        # Add model vies to the admin console (again, with app context)
        admin.add_views(*auth_blueprint.model_views)

    return(app)

当前结果

Association Proxy column is blank :(

2 个答案:

答案 0 :(得分:0)

由于您使用的是中级班KeywordPapercreator应该创建KeywordPaper个实例,而不是Keyword
在尝试像Paper.keywords += ["keyword"]这样的事情时,它实际上会导致运行时错误 所以你想要的是:

creator=lambda kw: KeywordPaper(keyword=Keyword(keyword=kw))

答案 1 :(得分:0)

嘿,有人读这个......

在使用flask admin 时,使用关联代理无缘无故地进行了很多工作。所以,我只是将关键字关系转换为正常的多对多关系。所以,我猜问题已经解决了。