带有关系的Flask-WTForms和SQLAalchemy SelectField

时间:2016-03-23 13:50:20

标签: flask sqlalchemy flask-sqlalchemy flask-wtforms

我正在尝试从表单中获取数据并使用SQLAlchemy将其发布到数据库我与产品模型中显示的类别和品牌模型有关系。但我得到一个错误:
AttributeError:' int'对象没有属性' _sa_instance_state' 我不确定,但我认为返回的是一个Category()对象,我必须传递和id到实例化的Product()对象 这可能有什么问题?

模型

class Product(db.Model):
  # Table name
  __tablename__ = 'products'
  # Main Fields
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(255), nullable=False)
  slug = db.Column(db.String(255), nullable=False, unique=True)
  description = db.Column(db.Text(255), nullable=True)
  active = db.Column(db.Boolean)
  # Timestamps
  created = db.Column(db.DateTime(), default=datetime.utcnow)
  updated = db.Column(db.DateTime(), default=datetime.utcnow,
                      onupdate=datetime.now)
  # ForeignKeys
  category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
  brand_id = db.Column(db.Integer, db.ForeignKey('brands.id'))
  # Backref Relations
  category = db.relationship('Category', backref='products')
  brand = db.relationship('Brand', backref='products')

  def __repr__(self):
      return self.name

  def __unicode__(self):
      return self.name

形式

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)

1 个答案:

答案 0 :(得分:3)

form.category.dataform.brand.data是ID。您需要将其作为category_idbrand_id而不是categorybrand传递。

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)