Flask-Admin с дополнительным полем в отношениях Многие ко Многим - PullRequest
0 голосов
/ 04 октября 2018

У меня есть две таблицы: "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))

builtins.Exception

Исключение: столбец формы находится в другой таблице и требует inline_models: Ingrediente.desc

Я много исследовал inline_models, но не нашел ничего, что решило бы эту проблему

1 Ответ

0 голосов
/ 05 октября 2018

Проблема в том, что 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]

Это поле, которое позволяет добавлять к нему элементы, такие как теги.

...