Flask 带关系的表单和SQLAalchemy SelectField

Flask 带关系的表单和SQLAalchemy SelectField,flask,sqlalchemy,flask-sqlalchemy,flask-wtforms,Flask,Sqlalchemy,Flask Sqlalchemy,Flask Wtforms,我试图从表单中获取数据,并使用SQLAlchemy将其发布到数据库。我与产品模型中所示的类别和品牌模型有关系。但我得到一个错误: AttributeError:“int”对象没有属性“\u sa\u instance\u state” 我不确定,但我认为返回的是Category()对象,我必须向实例化的Product()对象传递和id 这里可能出了什么问题 模型 形式 看法 form.category.data和form.brand.data是ID。您需要将它们作为category\u id和b

我试图从表单中获取数据,并使用SQLAlchemy将其发布到数据库。我与产品模型中所示的类别和品牌模型有关系。但我得到一个错误:
AttributeError:“int”对象没有属性“\u sa\u instance\u state” 我不确定,但我认为返回的是Category()对象,我必须向实例化的Product()对象传递和id 这里可能出了什么问题

模型 形式 看法
form.category.data
form.brand.data
是ID。您需要将它们作为
category\u id
brand\u id
传递,而不是
category
brand

new_product = Product(name=form.name.data,
                          slug=form.slug.data,
                          description=form.description.data,
                          active=form.active.data,
                          category_id=form.category.data,
                          brand_id=form.brand.data)

非常感谢您的回答,它非常有效。我试图通过category=form.category.data.id以错误的方式完成它。。。谢谢
class ProductForm(Form):
  name = StringField('Name', validators=[Required(), Length(1, 255)])
  slug = StringField('Slug', validators=[Required(), Length(1, 255)])
  description = StringField('Description', validators=[Required(), Length(1, 255)])
  active = BooleanField('Active')
  category = SelectField('Category', coerce=int)
  brand = SelectField('Brand', coerce=int)
  submit = SubmitField('Add Product')
@inventory.route('/product/new/', methods=['GET', 'POST'])
def add_product():
  form = ProductForm()
  categories = [(c.id, c.name) for c in Category.query.all()]
  brands = [(b.id, b.name) for b in Brand.query.all()]
  form.category.choices = categories
  form.brand.choices = brands
  if form.validate_on_submit():
    new_product = Product(name=form.name.data,
                          slug=form.slug.data,
                          description=form.description.data,
                          active=form.active.data,
                          category=form.category.data,
                          brand=form.brand.data)
    db.session.add(new_product)
    db.session.commit()
    flash('New Product has been added')
    return redirect(url_for('inventory.list_products'))
return render_template('inventory/form.html', form=form)
new_product = Product(name=form.name.data,
                          slug=form.slug.data,
                          description=form.description.data,
                          active=form.active.data,
                          category_id=form.category.data,
                          brand_id=form.brand.data)