2016-03-23 71 views
1

我想從表單中獲取數據並使用SQLAlchemy將其發佈到數據庫我有一個與產品模型中顯示的類別和品牌模型的關係。但我得到一個錯誤:
AttributeError:'int'對象沒有屬性'_sa_instance_state' 我不知道,但我認爲是什麼被返回是一個類別()對象,我必須傳遞和ID實例化產品()對象 這裏有什麼問題?Flask-WTForms和SQLAalchemy與關係的SelectField

模型
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

form.category.dataform.brand.data是IDS。您需要將它們傳遞爲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) 
+0

非常感謝您的答案,完美工作我試圖通過category = form.category.data.id錯誤的方式做...感謝很多 –