从Flask中的视图向表中添加数据时出现错误。我想要更新的表与另一个模型有ForeignKey关系。但是我正在尝试更新子模型。以下是一个简单的案例:
型号:
class Student(db.Model):
__tablename__='student'
....
package = package = relationship('Package', backref=backref('student'))
....
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class Package(db.Model):
__tablename__ = 'package'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
student_id = db.Column(db.Integer, ForeignKey('student.id'))
stripe_id = db.Column(db.String(45))
student_email = db.Column(db.String(20))
subscription_date = db.Column(db.DateTime, default=today)
expiry_date = db.Column(db.DateTime, default=deadline)
is_active = db.Column(db.Boolean, default=True)
planname = relationship('Plan', backref=backref('package'))
package_price = db.Column(db.Integer)
coupon = db.Column(db.String(12))
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
我的观点:
@app.route('/yearlychargedrec', methods=['GET', 'POST'])
def yearly_charged_rec():
if not user_authorized():
return redirect('/')
# customer
stripe_token = request.form['stripeToken']
email = request.form['stripeEmail']
customer = stripe.Customer.create(
email=email,
source=request.form['stripeToken']
)
try:
subscription = stripe.Subscription.create(
customer=customer.id,
plan="yearlyrec",
)
except stripe.error.CardError as e:
# The card has been declined
body = e.json_body
err = body['error']
if request.method == 'POST':
# email = email
package = Package(
is_active=True,
planname = 'yearlyrec',
)
db.session.add(package)
db.session.commit()
return render_template('/profile/charge/monthlycharge.html')
错误:
TypeError: Incompatible collection type: str is not list-like
答案 0 :(得分:1)
Package and Plan模型有关系,所以下面的行
planname = relationship('Plan', backref=backref('package'))
你在Package模型中为Plan模型添加了一个名为package
的属性,这个属性引用了一个Package而不是Plan,所以你不能创建这样的包对象。
解决方案在Plan模型上应该有相同的关系,让我们说你的计划类有这样的东西:
planname= relationship('Package', backref=backref('plan'))
现在您可以按如下方式创建Package对象:
plan = Plan(name='yearlyrec')
package = Package(is_active=True, plan=plan)
当然,您可以在此方案中查询和使用现有的Plan对象。