具有多对多关系的附加字段的 Flask-Admin

Car*_*ues 4 python flask python-3.x flask-sqlalchemy flask-admin

我有两个表:“产品”、“成分”和“产品成分”

class ProductIngredient(db.Model):
    __tablename__ = "product_ingredient"
    id = db.Column(db.Integer(), primary_key=True)
    product_id = db.Column('product_id', db.Integer, db.ForeignKey('product.id'))
    ingredient_id = db.Column('ingredient_id', db.Integer, db.ForeignKey('ingredient.id'))
    amount = db.Column(db.DECIMAL(10, 3))


class Ingredient(db.Model):
    __tablename__ = "ingredient"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    desc = db.Column(db.Text)


class Produto(db.Model):
    __tablename__ = "product"

    id = db.Column(db.Integer, primary_key=True)
    desc = db.Column(db.String(20))
    ingredients = db.relationship('Ingredient', secondary='product_ingredient', backref=db.backref('product', lazy='dynamic'))
Run Code Online (Sandbox Code Playgroud)

请注意,在 ProductIngredient 类中有一个数量字段,它将获取构成每个产品的每种成分的数量

在管理员中设置字段,我收到以下错误

class ProdMV(ModelView):
    column_display_pk = False
    form_columns = [Product.desc, Ingredient.name, ProductIngredient.amount]
    column_auto_select_related = True
    column_hide_backrefs = False


admin.add_view(ProdMV(Product, db.session))
Run Code Online (Sandbox Code Playgroud)

内置异常

例外:表单列位于另一个表中并且需要 inline_models: Ingrediente.desc

我对 inline_models 进行了大量研究,但没有发现任何解决此问题的方法

Ser*_*bin 5

问题是Product对象可以有多种成分,并且不能在一个表单字段中指定它们。所以flask_admin 提示你应该使用inline_models. 您需要向ProductIngredient模型添加关系:

class ProductIngredient(db.Model):
    __tablename__ = 'product_ingredient'

    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'))
    ingredient_id = db.Column(db.Integer, db.ForeignKey('ingredient.id'))
    amount = db.Column(db.DECIMAL(10, 3))

    product = db.relationship('Product', backref='products')
    ingredient = db.relationship('Ingredient', backref='ingredients')
Run Code Online (Sandbox Code Playgroud)

你的ProductMV遗嘱是这样的:

class ProductMV(ModelView):
    form_columns = ('desc',)
    inline_models = ((
        ProductIngredient,
        {
            'form_columns': ('id', 'amount', 'ingredient'),
        }
    ),)
Run Code Online (Sandbox Code Playgroud)

如果你没有ProductIngredient.amount字段,你可以输入:

form_columns = [Product.desc, Product.ingredients]
Run Code Online (Sandbox Code Playgroud)

这构成了一个允许向其添加项目(如标签)的字段。