Jon*_*tan 4 entity-attribute-value flask wtforms
我有三个表:components,attributes和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))
Run Code Online (Sandbox Code Playgroud)
这些是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))
Run Code Online (Sandbox Code Playgroud)
我的问题是我希望看到属性名称作为值字段的标签(替换“值”)。我一直试图围绕WTForms在内部的工作方式,但是我看不出任何明显的方法可以做到这一点。
任何提示表示赞赏。如果我只能在渲染value字段时握住AttributeValue对象,那么我什至可以使用仅渲染自定义标签的hack。
好的,所以我想出了一个解决方案,该解决方案有点类似于adarsh对他的回答的第二条评论,但是覆盖了FormField使用的Form的初始化:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2613 次 |
| 最近记录: |