Flask 使WTForms从数据库模型设置字段标签

Flask 使WTForms从数据库模型设置字段标签,flask,wtforms,entity-attribute-value,Flask,Wtforms,Entity Attribute Value,我有三个表:组件、属性和属性值。每个组件可以有许多属性值。每个属性值都属于一个属性。是的,这是可怕的EAV模式 我创建了以下两种形式: class AttributeValueForm(Form): attribute = HiddenField() value = StringField('Value') class ComponentForm(Form): ... non-related fields left out ... attribute_value

我有三个表:组件、属性和属性值。每个组件可以有许多属性值。每个属性值都属于一个属性。是的,这是可怕的EAV模式

我创建了以下两种形式:

class AttributeValueForm(Form):
    attribute = HiddenField()
    value = StringField('Value')

class ComponentForm(Form):
    ... non-related fields left out ...
    attribute_values = FieldList(FormField(AttributeValueForm))
以下是SQLAlchemy模型:

class Component(db.Model):
    __tablename__ = 'components'
    id = db.Column(db.Integer, primary_key=True)
    ... non-related columns left out ...

class AttributeValue(db.Model):
    __tablename__ = 'attribute_values'
    id = db.Column(db.Integer, primary_key=True)
    value = db.Column(db.String)

    attribute_id = db.Column(db.Integer, db.ForeignKey('attributes.id'))
    attribute = db.relationship('Attribute', backref='attribute_values'))

    component_id = db.Column(db.Integer, db.ForeignKey('components.id'))
    component = db.relationship('Component', backref='attribute_values'))

def Attribute(db.Model):
    __tablename__ = 'attributes'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
我的问题是,我希望看到属性的名称作为值字段的标签(替换“value”)。我一直在想WTForms是如何在内部工作的,但我看不到任何明显的方法


任何提示,不胜感激。我甚至可以用一个黑客来渲染一个自定义标签,如果我只能在呈现值字段时获取属性值对象。

可以考虑从

使用<代码>模型窗体< /代码>。 您可以很容易地用模型定义表单

比如:

class AttributeValueForm(ModelForm):
    class Meta:
        model = Attribute
        only = (... columns that you want to include ...)

好的,所以我提出了一个解决方案,这有点类似于adarsh对其答案的第二个评论,但覆盖了FormField使用的表单的init

class AttributeValueForm(Form):
    value = StringField('Unnamed attribute')

    def __init__(self, *args, **kwargs):
        super(AttributeValueForm, self).__init__(*args, **kwargs)
        if 'obj' in kwargs and kwargs['obj'] is not None:
            self.value.label.text = kwargs['obj'].attribute.name

谢谢,但我不想编辑或更改属性类型/名称:我只想更改值字段的标签。我已经在Attribute.name上使用了QuerySelectField,它可以正常工作。我仍然对您的问题有点困惑,但是如果我理解正确,您可以在构建表单时传递
AttributeValue
对象,然后像这样更改标签
form.value.label=attribute\u value\u object。无论什么
每个组件都可能有许多AttributeValue,它们由WTForms使用FieldList自动填充(请参见上面的ComponentForm)。因此,我无法访问在构建表单后创建每个AttributeValueForm实例的AttributeValueInstance(除非有办法找到构建表单后用于填充表单的对象)。当然,我可以访问所有AttributeValue,但我不知道其中哪一个用于填充每个AttributeValue表单。