Random value for field by default?

150 views
Skip to first unread message

AF

unread,
Jun 21, 2009, 4:32:12 PM6/21/09
to sqlalchemy
Hello,

Perhaps this is more of a Python question that SQLalchemy...... but...


How can I assign a random number to a DB field by default?


I tried:
default = random.randrange(1000,10000) on the table definition, but I
get the same number each time?

Ideas?

Bobby Impollonia

unread,
Jun 21, 2009, 4:47:46 PM6/21/09
to sqlal...@googlegroups.com
default = lambda: random.randrange(1000,10000)

allen.fowler

unread,
Jun 21, 2009, 4:50:04 PM6/21/09
to sqlalchemy
OK, never mind... I solved it.

The default = random.randrange(1000,10000) code was happily taking the
static return value. Duh.

I changed it to:

default = lambda: random.Random().randrange(2000,8000)

I dunno if the extra Random() is needed, but it can't hurt, right?

allen.fowler

unread,
Jun 21, 2009, 4:53:21 PM6/21/09
to sqlalchemy

> default = lambda: random.randrange(1000,10000)
>

Seems we crossed in the interwebs.. :)

Is it safe to do this, or do you need to do default = lambda:
random.Random()randrange(1000,10000) ?

I ask since I have several tables that this needs to be applied to.

Thank you

Bobby Impollonia

unread,
Jun 21, 2009, 5:10:13 PM6/21/09
to sqlal...@googlegroups.com
Yes, it is safe. Python's underlying random number generation is
threadsafe. There is no need to create a new RNG each time to generate
a single number.
Reply all
Reply to author
Forward
0 new messages