WTForms-Alchemy QuerySelectField无法使用Model实例填充model_id字段

时间:2017-05-04 15:18:49

标签: python sqlalchemy wtforms

我希望WTForms-Alchemy表单填充template_id模型的Cloaker字段。但是,我在调用Template时收到SQLAlchemy无法调整populate_obj的错误。我认为我的关系设置正确。为什么没有正确设置所选模板的表单?

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)出现以下错误:

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''}]

1 个答案:

答案 0 :(得分:0)

您正在尝试填充外键字段template_id,而不是关系。

QuerySelectField按ID选择实例,而不是id。将您的字段命名为template。修复您的关系backref称为template,因为Cloaker.cloaker没有多大意义。 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(...)