__init __()得到了一个意想不到的关键字参数' author'一对多

时间:2016-11-22 22:09:16

标签: python one-to-many flask-sqlalchemy

那么,我试图引用用户帖子?我一直收到这个错误

错误

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'

我试图引用用户的帖子。

Models.py

from app import app, db, bcrypt, slugify, flask_whooshalchemy, JWT, jwt_required, current_identity, safe_str_cmp
from sqlalchemy import Column, Integer, DateTime, func
from app import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)

import datetime


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(20), unique=True)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def __init__(self, username, password):
        self.username = username
        self.password = bcrypt.generate_password_hash(password, 9)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return  (self.id)

    def __repr__(self):
        return '<User %r>' % self.username


class Post(db.Model):
    __tablename__ = "posts"

    id = db.Column(db.Integer,  primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    # slug = db.Column(db.String(80), index=True, nullable=True)

    time_created = Column(DateTime(timezone=True), server_default=func.now())
    time_updated = Column(DateTime(timezone=True), onupdate=func.now())

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

        # self.slug = slugify(title).lower()

我很困惑,我一直在引用flask mega tutorial我没有真正成功,有没有人有任何建议,我即将疯狂

2 个答案:

答案 0 :(得分:2)

您需要的是:

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

正如凯尔所提到的,将user_id参数添加到__init__的{​​{1}}:

Post

因为您的帖子包含def __init__(self, title, body, user_id): ... self.body = body self.user_id = user_id ... ,而不是user_id

author

您的用户有class Post(db.Model): ... user_id = db.Column(db.Integer, db.ForeignKey('user.id')) ...

id

答案 1 :(得分:2)

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

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

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