Abdxrrahman
Abdxrrahman

Reputation: 35

How to append a value into Flask-Sqlalchemy

I have a question, I have ran into an issue where I can't append anything to PickleTypes.

How I made the class.

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    password = db.Column(db.String(80))
    liked_posts = db.Column(db.PickleType())

It does not append through this.

@app.route('/point-give/<id>', methods=['POST'])
def point_give(id):
    list_of_liked = current_user.liked_posts
    p = Post.query.filter_by(id=int(id)).first()
    u = User.query.filter_by(id=current_user.id).first()
    print(list_of_liked)
    
    for i in list_of_liked:
        if i.id == int(id):
            return redirect(url_for('index'))

    u.liked_posts.append(int(id))
    p.likes = p.likes + 1
    db.session.commit()
    return redirect(url_for('index'))

Upvotes: 0

Views: 197

Answers (1)

Kate
Kate

Reputation: 1836

Well, does your code even reach the append statement ? Because there is a redirect to index in your loop if this condition is met: if i.id == int(id):

Most likely it has to do with the values and your conditions. Add a print after the for loop to see if the code actually gets that far.

NB: casting id to integer is will raise an exception if a string is entered. Rewrite your route like this instead:

@app.route('/point-give/<int:id>', methods=['POST'])

Thus, if a string is entered as a parameter, this will raise a 404 error.

Upvotes: 1

Related Questions