1
嗨我想做一個簡單的應用程序,用戶有能力創建新的雞尾酒。因此,我有兩個模型與多種關係創建一個新的對象返回AttributeError:'列表'對象沒有屬性'_sa_instance_state'
from . import db
assoc_table = db.Table('association',
db.Column('ingredient_id', db.Integer, db.ForeignKey('ingredients.id')),
db.Column('cocktail_id', db.Integer, db.ForeignKey('cocktails.id'))
)
class Ingredient(db.Model):
__tablename__ = 'ingredients'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
cost_price = db.Column(db.Float, default=0.0)
cocktails = db.relationship('Cocktail',
secondary=assoc_table,
backref=db.backref('ingredients'),
lazy='dynamic')
class Cocktail(db.Model):
__tablename__ = 'cocktails'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
serv_percentage = 0.25
sell_price = db.Column(db.Float)
而在視圖中,我發送表單,如果它是一個GET請求。如果它是一個POST,我嘗試創建雞尾酒對象,然後將它保存在數據庫:
@main.route('/new', methods=['GET', 'POST'])
def new():
form = CocktailForm()
form.ingredients.choices = [(i.id, i.name) for i in Ingredient.query.all()]
if form.validate_on_submit():
cocktail_name = form.name.data
cocktail_ingredients = Ingredient.query.filter(Ingredient.id.in_(form.ingredients.data)).all()
c = Cocktail()
c.name = form.name.data
c.ingredients.append(cocktail_ingredients)
db.session.add(c)
db.session.commit()
return redirect(url_for('.index'))
return render_template('new.html', form=form)
我得到AttributeError的:
在嘗試創建一個空的'list' object has no attribute '_sa_instance_state'
Cocktail:
行
c = Cocktail()
我沒有線索是什麼問題。
我檢查了很多答案,通常是有關人際關係,所以我真的不知道有什麼錯我的代碼
這裏是窗體類,但我認爲這不是問題:
class CocktailForm(Form):
name = StringField('What is the coktail\'s name?', validators=[Required()])
ingredients = SelectMultipleField('Ingredients', coerce=int)
submit = SubmitField('Submit')
謝謝
謝謝@univerio我看不到它!我會upvote你的答案,但我不能:/ –
@ERodriguez請接受答案,如果它解決了你的問題。謝謝! – univerio
答案已接受! :) –