0

I was wondering if it's possible to delete some random rows from a Query Object before doing a bulk update.

Example:

writerRes = self.session.query(table)
writerRes = writerRes.filter(table.userID==3)
-> Delete some of the rows randomly
writerRes.update({"userID": 4})

Is there an easy way to do that?

1 Answer 1

1

Selecting random row with SA depends on the database. Based on that answer.

Postgresql and Sqlite3:

number_of_random_rows = 3
rand_rows = session.query(table.userid).order_by(func.random()).limit(number_of_random_rows).subquery()
session.query(table).filter(table.userid.in_(rand_rows)).delete(synchronize_session='fetch')

MySQL:

number_of_random_rows = 3
rand_rows = session.query(table.userid).order_by(func.rand()).limit(number_of_random_rows).subquery()
session.query(table).filter(table.userid.in_(rand_rows)).delete(synchronize_session='fetch')

...

Sign up to request clarification or add additional context in comments.

3 Comments

I made a mistake ... The code looks great but it doesn't work for me. I get this error OperationalError: (OperationalError) only a single result allowed for a SELECT that is part of an expression. Any Idea?
What database are you using and what code are you running? I only tested it on SQLite & Postgres.
I'm using the SQLite Database and I'm running the code you posted except that I filter the rows before running your code: writerRes = writerRes.filter(table.userID==4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.