reznov11
reznov11

Reputation: 153

Delete one row from database with SqlAlchemy Flask?

Am trying to delete a user from my subscribers list , but the whole subscribers deleting automatically .

Here is my subscribe function:

def subscribe(self, user_id):
    if not self.is_subscriber(user_id):
        db.engine.execute(
            subscribers.insert(),
            client_id = self.id,
            user_id = user_id
        )
        db.session.commit()
    else:
        return False

The unsubscribe function:

def unsubscribe(self, user_id):
    if self.is_subscriber(user_id):
        db.engine.execute(
            subscribers.delete(),
            client_id = self.id,
            user_id = user_id
        )
        db.session.commit()
    else:
        return False

By that if i tried to unsubscribe it should delete that specific user , but in my situation the whole users get deleted from the table, why is that, please, anybody can help to solve the problem here ??

Edit:

If i tried to delete the client_id from the query and just to delete the user_id, i get this error:

UnmappedInstanceError: Class '__builtin__.int' is not mapped

also with db.session.delete(user_id) command !! .

Also i've created this function, which by i get also the same error:

def unsubscriber(self, user_id):
    select_subscribers = subscribers.select(
            db.and_(
                subscribers.c.user_id == user_id,
                subscribers.c.client_id == self.id
            )
    )
    rs = db.engine.execute(select_subscribers)
    return False if rs.rowcount == 0 else db.session.delete(user_id),
    db.session.commit()

Upvotes: 2

Views: 8700

Answers (1)

abigperson
abigperson

Reputation: 5372

If you're using flask-sqlalchemy you can simplify a lot of this to leverage the power of sqlalchemy. FWIW you shouldn't be accessing the engine directly like this unless you have a more advanced use case you should use the session

E.g. You have mapped your data model like this:

class Subscriber(db.Model):
    user_id = db.Column(db.Integer, primary_key=true)
    client_id = ....
    ....

    # method to add new subscriber
    def __init__(self, user_id, client_id)
        self.user_id = user_id
        self.client_id = client_id

@app.route('/subscribe/')
def subscribe():
    # add a subscriber with user id 21, client 543
    new = Subscriber(21, 543)
    db.session.add(new)
    db.session.commit()

@app.route('/unsubscribe/')
def unsubscribe():
    # remove subscriber
    Subscriber.query.filter_by(user_id=21, client_id=543).delete()
    db.session.commit()

Upvotes: 4

Related Questions