1

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 ?

1
  • 1
    Did you actually execute func.setseed(0)? In your example you don't. func.setseed(0) just creates a function expression object. It is rendered to suitable SQL when compiled and executed as a part of a query. Commented Mar 19, 2018 at 15:18

1 Answer 1

1

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

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

1 Comment

Thanks. My concerns was about the argument of the rand function, and why the setseed seemed to have no effect. The MySQL doc about the rand function is ambiguous as the argument is said to be a integer but later its description is a number between 0 and 1. I tried both and no exception was raised.

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.