"一对多中,'init()'收到了意外的关键字参数'author'"

2024-06-01 00:59:00 发布

您现在位置:Python中文网/ 问答频道 /正文

那么,我想引用一个用户的帖子?我总是犯这个错误

错误

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db, models
/usr/local/lib/python2.7/dist-packages/Flask-0.11.1-py2.7.egg/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead.
  .format(x=modname), ExtDeprecationWarning
>>> u = models.User.query.get(2)
>>> p = models.Post(title='barn owl', body='thompson', author=u)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'author'

我试着参考用户的帖子。在

模型.py

^{pr2}$

我很困惑,我一直在引用flask mega tutorial我没有真正成功,有人有什么建议,我要发疯了


Tags: 用户pydefaultflasksqlalchemyonmodelstype
2条回答

或者只需将author作为关系添加,并将author作为参数添加到__init__方法中

# inside Post definition
author = db.relationship("User")

def __init__(self,title,body,author):
    self.author = author

你需要的是:

p = models.Post(title='barn owl', body='thompson', user_id=u.id)
#                                                  ^^^^^^^ ^ ^^

正如凯尔提到的,将user_id参数添加到Post__init__

^{pr2}$

因为您的帖子包含user_id,而不是author

class Post(db.Model):
    ...
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    ...

您的用户有一个id

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...

相关问题 更多 >