看了几天的文档,搜索无果,再看源码,发现了,inline-models的使用说明。
英文没有水平,看起来,太吃力。在这里记录一下。
之前的学习中,只知道要使用inline-models,但不知道怎么使用,使用了根没用一样,甚至还报错。
在编辑表单中,显示的外键关系的数据,为一个下拉菜单,显然这样不是我想要的。无论你改变,uselist=False,只是从多选变成了单选。
下面看一下,源码的说明:
inline_models = None """ Inline related-model editing for models with parent-child relations. Accepts enumerable with one of the following possible values: 1. Child model class:: class MyModelView(ModelView): inline_models = (Post,) 2. Child model class and additional options:: class MyModelView(ModelView): inline_models = [(Post, dict(form_columns=['title']))] 3. Django-like ``InlineFormAdmin`` class instance:: from flask_admin.model.form import InlineFormAdmin class MyInlineModelForm(InlineFormAdmin): form_columns = ('title', 'date') class MyModelView(ModelView): inline_models = (MyInlineModelForm(MyInlineModel),) You can customize the generated field name by: 1. Using the `form_name` property as a key to the options dictionary:: class MyModelView(ModelView): inline_models = ((Post, dict(form_label='Hello'))) 2. Using forward relation name and `column_labels` property:: class Model1(Base): pass class Model2(Base): # ... model1 = relation(Model1, backref='models') class MyModel1View(Base): inline_models = (Model2,) column_labels = {'models': 'Hello'} By default used ManyToMany relationship for inline models. You may configure inline model for OneToOne relationship. To achieve this, you need to install special ``inline_converter`` for your model:: from flask_admin.contrib.sqla.form import \ InlineOneToOneModelConverter class MyInlineModelForm(InlineFormAdmin): form_columns = ('title', 'date') inline_converter = InlineOneToOneModelConverter class MyModelView(ModelView): inline_models = (MyInlineModelForm(MyInlineModel),) """
在说明中,看到inline-models默认使用在多对多的关系中。如果想使用inline-models到一对一关系中,需要
from flask_admin.contrib.sqla.form import InlineOneToOneModelConverter
from flask_admin.model import InlineFormAdmin
class MyInlineModelForm(InlineFormAdmin): # 需要导入,而不是你自己定义的
form_columns = ('title', 'date')
inline_converter = InlineOneToOneModelConverter
class MyModelView(ModelView):
inline_models = (MyInlineModelForm(MyInlineModel),) # 这个是你要设置行内编辑的 类名(自己的模型类)
至此,一对一关系中的编辑表单中,已经可以显示,对应的列了。不再是下拉菜单,而是正常的input 文本了