[英]WTForms-Alchemy QuerySelectField can't populate model_id field with Model instance
I want a WTForms-Alchemy form to populate the template_id
field of the Cloaker
model. 我想要WTForms-Alchemy表单来填充
Cloaker
模型的template_id
字段。 However, I get an error that SQLAlchemy can't adapt Template
when calling populate_obj
. 但是,我收到一个错误,当调用
populate_obj
时,SQLAlchemy无法适应Template
。 I think my relationship is set up correctly. 我认为我的关系建立正确。 Why isn't the form setting the selected template correctly?
为什么表单无法正确设置所选模板?
class Template(db.Model):
id = db.Column(db.Integer, primary_key=True)
cloaker = relationship('Cloaker', backref='cloaker')
class Cloaker(db.Model):
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.Integer, db.ForeignKey('template.id'), nullable=False)
class CloakerForm(ModelForm):
class Meta:
model = Cloaker
template_id = QuerySelectField(
query_factory=lambda: Template.query.all(),
get_pk=lambda a: a.id,
get_label=lambda a: a.name,
allow_blank=True,
blank_text=u'-- please choose --'
)
form.populate_obj(cloaker)
gives the following error: form.populate_obj(cloaker)
给出以下错误:
ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'Template' [SQL: 'INSERT INTO cloaker (status, created_at, updated_at, domain, safepage_url, moneypage_url, template_id, "user", company, country, connection_id, lp) VALUES (%(status)s, %(created_at)s, %(updated_at)s, %(domain)s, %(safepage_url)s, %(moneypage_url)s, %(template_id)s, %(user)s, %(company)s, %(country)s, %(connection_id)s, %(lp)s) RETURNING cloaker.id'] [parameters: {'status': None, 'domain': u'1', 'moneypage_url': u'asdv', 'template_id': <automata.cloaker.models.Template object at 0x10fd87990>, 'country': u'', 'created_at': datetime.datetime(2017, 5, 4, 23, 12, 3, 380155), 'connection_id': u'', 'updated_at': datetime.datetime(2017, 5, 4, 23, 12, 3, 380167), 'safepage_url': u'sdv', 'user': u'asdva', 'lp': u'', 'company': u''}]
You're trying to populate the foreign key field, template_id
, not the relationship. 您正在尝试填充外键字段
template_id
,而不是关系。
A QuerySelectField
selects an instance by id, not the id. QuerySelectField
通过ID而不是ID选择实例。 Name you field template
. 为您命名字段
template
。 Fix your relationship backref to be called template
, since Cloaker.cloaker
doesn't make much sense. 修正您的关系backref被称为
template
,因为Cloaker.cloaker
并没有多大意义。 populate_obj
will set the Cloaker.template
relationship to the selected Template
, which SQLAlchemy will handle correctly. populate_obj
会将Cloaker.template
关系设置为所选的Template
,SQLAlchemy将正确处理该关系。
class Template(db.Model):
id = db.Column(db.Integer, primary_key=True)
class Cloaker(db.Model):
id = db.Column(db.Integer, primary_key=True)
template_id = db.Column(db.ForeignKey(Template.id), nullable=False)
template = db.relationship(Template)
class CloakerForm(ModelForm):
template = QuerySelectField(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.