python org AttributeError:'int'對像沒有屬性'_sa_instance_state'



sqlalchemy flask multiple database (2)

問題是這樣的:

post = Post(body=form.body.data,
            timestamp=datetime.utcnow(),
            thread=thread.id,
            author=g.user.id)

您希望使用ORM對象,而不是主鍵列:

post = Post(body=form.body.data,
            timestamp=datetime.utcnow(),
            thread=thread,
            author=g.user)

該錯誤意味著整數被解釋為ORM對象。

我正在使用Flask在論壇模板上工作。 當我嘗試使用表單在瀏覽器中創建新線程時,SQLAlchemy會拋出AttributeError。 當我嘗試與Forum-to-Thread實現一對多的關係以及與Thread-to-User的一對多關係時,問題出現了。

models.py

class User(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(32), index=True, unique=True)
  password = db.Column(db.String(32), index=True)
  email = db.Column(db.String(120), index=True, unique=True)
  role = db.Column(db.SmallInteger, default=ROLE_USER)

  posts = db.relationship('Post', backref='author', lazy='dynamic')

class Forum(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  title = db.Column(db.String(128))
  description = db.Column(db.Text)

  threads = db.relationship('Thread', backref='forum', lazy='dynamic')

class Thread(db.Model):

  id = db.Column(db.Integer, primary_key=True)
  title = db.Column(db.String(128))
  author= db.Column(db.String(32))
  timestamp = db.Column(db.DateTime)
  forum_id = db.Column(db.Integer, db.ForeignKey('forum.id'))

  posts = db.relationship('Post', backref='thread', lazy='dynamic')

class Post(db.Model):

  id = db.Column(db.Integer, primary_key=True)
  body = db.Column(db.Text)
  timestamp = db.Column(db.DateTime)
  thread_id = db.Column(db.Integer, db.ForeignKey('thread.id'))
  user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

所有新帖子/帖子都在views.py中處理

views.py

@app.route('/forum/id=<id>/submit', methods=['GET','POST'])
@login_required
def new_thread(id):
  form = ThreadForm()
  forum = Forum.query.filter_by(id=id).first()
  if form.validate_on_submit():
    thread = Thread(title=form.title.data,
                    author=g.user.username,
                    timestamp=datetime.utcnow())
    db.session.add(thread)
    db.session.flush()
    post = Post(body=form.body.data,
                timestamp=datetime.utcnow(),
                thread=thread.id,
                author=g.user.id)
    db.session.add(post)
    db.session.commit()
    flash('Post successful.')
    return redirect(url_for('forum_index', id=id))
  return render_template('forum/thread_submit.html', title=forum.title, form=form) 

Answer #1

也可能是字段名稱未正確指向:

class ThreadFrom(FlaskForm):

    title = StringField('title', [validators.Length(max=128)])
    author= StringField('author', [validators.Length(max=32)])
    timestamp = DateField()
    forum = SelectField()

而不是forum應該是forum_id





flask-sqlalchemy