我试图仅显示当前登录用户在网站上发布的帖子。我相信我需要filter_by关键字。我浏览了SQlalchemy的文档,但是语法仍然很困难,无法使它起作用:
进口:
from project.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
路线:
@app.route("/history")
def history():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.end_date.desc()).filter_by(User.id==current_user)
return render_template('history.html', posts=posts, title='About')`
用户/帖子页面:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)`
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
identification = db.Column(db.String(10), nullable=False)
date_posted = db.Column(db.Date, nullable=False, default=datetime.utcnow)
notes = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)`
错误: 当我键入filter_by(User.id == current_user)时:
TypeError: filter_by() takes 1 positional argument but 2 were given
当我键入filter_by(user.id == current_user)时,不确定用户是否应该大写:
NameError: name 'user' is not defined
当我键入 filter_by(user_id = current_user)
sqlalchemy.exc.ArgumentError: Object User('test', 'test@yahoo.com'), '1' is not legal as a SQL literal value
感谢您的帮助
答案 0 :(得分:-1)
如果您复制错误,可能会对我们有帮助。
我认为您使用的是filter_by错误的方式。您需要使用列名作为参数:
def address_x(vals):
val = {
'street': None if not str(vals['Street']) else vals['Street'],
'city': None if not str(vals['City']) else vals['City'],
'state': None if not str(vals['State']) else state(vals['State']),
'postal_code': postal_code(str(vals['Zip_Code']))
}
return val
df['address'] = dataset[['Street', 'City', 'State', 'Zip_Code']].apply(address_x, axis=1)