Reputation: 409
I have a class user
in my database and I want to assign avatar_file_name
a random value every-time a new user is created essentially "on save". How can I accomplish this?
Array of Data that will randomly be chosen from
avatarImages = [
"blue-dino_128.png",
"brown-dino_128.png",
"green-dino_128.png",
"orange-dino_128.png",
"pink-dino_128.png",
"purple-dino_128.png",
]
This is the class and be default it selects a random string name from the array but I think there is a better way to accomplish this.
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
first_name = Column(String(50), nullable=False)
last_name = Column(String(50), nullable=True)
avatar_file_name = Column(String(100), nullable=True, default=random.choice(avatarImages)
Upvotes: 0
Views: 157
Reputation: 55620
default=random.choice(avatarImages)
is executed only once, so the same value will be selected for every user. To get a random selection for each user, make the call to random.choice
in a lambda
:
default=lambda: random.choice(avatarImages)
Upvotes: 1