Flask-Admin,具有多对多关系中的其他字段 [英] Flask-Admin with additional field in relationship Many to Many
问题描述
我有两个表:产品",成分"和产品成分"
I have two tables: "Product", "Ingredient" and "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类中有一个数量字段,该字段将提取构成每种产品的每种成分的数量
Note that in the ProductIngredient class there is an amount field, which would take the quantity of each ingredient that makes up each product
在admin中设置字段,出现以下错误
setting the fields in admin, I get the following error
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))
builtins.Exception
builtins.Exception
例外:表单列位于另一个表中,并且需要inline_models:Ingrediente.desc
Exception: form column is located in another table and requires inline_models: Ingrediente.desc
我对inline_models进行了很多研究,但没有找到解决该问题的方法
I researched a lot about inline_models but found nothing that solved this problem
推荐答案
问题是Product
对象可以具有多种成分,并且不能在一个表单字段中指定它们.因此flask_admin提示您应该使用inline_models
.您需要向ProductIngredient
模型添加关系:
The problem is that Product
object can have several ingredients and they cannot be specified in one form field. So flask_admin hints that you should use inline_models
. You need to add relationships to the ProductIngredient
model:
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
字段,则可以键入:
If you would not have ProductIngredient.amount
field you could just type:
form_columns = [Product.desc, Product.ingredients]
这将创建一个字段,允许在其中添加标签等项目.
This makes a field which allows adding items to it like tags.
这篇关于Flask-Admin,具有多对多关系中的其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!