【问题标题】:Flask-Admin with additional field in relationship Many to ManyFlask-Admin 与多对多关系中的附加字段
【发布时间】:2018-10-04 01:17:47
【问题描述】:

我有两个表:“Product”、“Ingredient”和“ProductIngredient”

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'))

请注意,在 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))

内置异常

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

我对 inline_models 进行了很多研究,但没有找到解决这个问题的方法

【问题讨论】:

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


    【解决方案1】:

    问题是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')
    

    你的ProductMV 看起来像这样:

    class ProductMV(ModelView):
        form_columns = ('desc',)
        inline_models = ((
            ProductIngredient,
            {
                'form_columns': ('id', 'amount', 'ingredient'),
            }
        ),)
    

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

    form_columns = [Product.desc, Product.ingredients]
    

    这会创建一个允许向其添加项目的字段,例如标签。

    【讨论】:

      猜你喜欢
      • 2012-03-25
      • 2011-05-25
      • 1970-01-01
      • 2021-10-14
      • 2011-10-13
      • 1970-01-01
      • 2017-01-10
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多