简体   繁体   中英

I am getting "AttributeError: 'int' object has no attribute 'filter'

I want this to be able to filter post by the CURRENT USER and delete it. Someone told me to use.WHERE instead of.FILTER but neither of them are working and I get an Attribute Error. How can I get this working?

By the way I am able to delete ALL user post with just db.session.query(Post).delete() but I want it so it only deletes posts for CURRENT_USER.ID (the user that is currently logged into my session)

I added my current models:

@login_required
def delete_all_post():
    if current_user.is_authenticated:
        db.session.query(Post).delete().filter(Post.user_id == current_user.id)
        db.session.commit()
        flash('All of your posts has been deleted!', 'success')
        return redirect(url_for('main.home'))```

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', {self.date_posted}')"

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(16), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

delete() return True/ False which is 0 or 1 which is int so you cannot do filter over it

try: db.session.query(Post).filter(Post.user_id == current_user.id).delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM