2016-03-23 20 views
1

フォームからデータを取得してSQLAlchemyを使用してデータベースにポストしようとしています。製品モデルに示されているカテゴリとブランドモデルとの関係があります。しかし、私はエラーが発生しています:
AttributeError: 'int'オブジェクトには '_sa_instance_state'属性がありません 私はよく考えていますが、返されているものはCategory()オブジェクトだと思います。 Product()オブジェクト ここで何が間違っていますか?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はIDです。 categorybrandではなく、category_idbrand_idとして渡す必要があります。

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

私はカテゴリ= form.category.data.idで間違った方法でやってみようとしていたあなたの答えにお礼をたくさん...ありがとう –

関連する問題