问题
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'))
Note that in the ProductIngredient class there is an amount field, which would take the quantity of each ingredient that makes up each product
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
Exception: form column is located in another table and requires inline_models: Ingrediente.desc
I researched a lot about inline_models but found nothing that solved this problem
回答1:
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')
And your ProductMV
will look something like this:
class ProductMV(ModelView):
form_columns = ('desc',)
inline_models = ((
ProductIngredient,
{
'form_columns': ('id', 'amount', 'ingredient'),
}
),)
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.
来源:https://stackoverflow.com/questions/52637653/flask-admin-with-additional-field-in-relationship-many-to-many