GuillaumeA
GuillaumeA

Reputation: 3545

How does the random func works in sqlalchemy in python (for MySQL databse)?

I did not find any answer in the doc so I ask you for help. I want to generate a random response from my database. To be reproducible, I set the seed and call a simple query this way:

func.setseed(0)
session.query(MyModel.id).order_by(func.random()).first()  #  --> returns 324
func.setseed(0)
session.query(MyModel.id).order_by(func.random()).first()  #  --> returns 736

As you can see, even after resetting the seed, the result is still different. However, I found a way to fix it, but I dont understand why:

func.setseed(0)
session.query(MyModel.id).order_by(func.random(0.1)).first()  #  --> returns 547
func.setseed(0)
session.query(MyModel.id).order_by(func.random(0.1)).first()  #  --> returns 547

What does the func.random argument mean ?

Upvotes: 1

Views: 1813

Answers (1)

Adriano Martins
Adriano Martins

Reputation: 1808

The func.random is actually a sqlalchemy.sql.functions.GenericFunction, which is a generic method that is not database-specific.

On a MySQL database, the argument passed to the random function acts as the seed - that's why it returns the same value.

You can read more about it here and here

Upvotes: 1

Related Questions