我有三个表:组件,属性和 attribute_values 。每个组件都可以有许多 attribute_values 。每个 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))
我的问题是,我希望将属性的名称视为值字段的标签(替换'值')。我一直试图围绕WTForms如何在内部工作,但我无法看到任何明显的方法来做到这一点。
任何提示都表示赞赏。如果我只能在渲染值字段时抓住AttributeValue对象,我甚至可以使用只渲染自定义标签的黑客。
答案 0 :(得分:4)
好的,所以我想出了一个解决方案,这有点类似于adarsh对他的回答的第二个评论,但是覆盖了FormField使用的Form的 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
答案 1 :(得分:0)
您可以考虑使用wtforms-alchemy
中的ModelForm
您可以非常轻松地使用模型定义表单。
类似的东西:
class AttributeValueForm(ModelForm):
class Meta:
model = Attribute
only = (... columns that you want to include ...)