在保存/创建 SQL Alchemy 中的列时为其赋值
我的数据库中有一个类 user
,我想在每次创建新用户时分配一个随机值 avatar_file_name
,本质上是“保存时”。我怎样才能做到这一点?
中随机选择的数据数组,默认情况下它会从数组中选择随机字符串名称,但我认为有更好的方法来实现此目的。
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",
]
将从该类
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
default=random.choice(avatarImages)
仅执行一次,因此将为每个用户选择相同的值。要为每个用户进行随机选择,请在lambda
中调用random.choice
: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 torandom.choice
in alambda
: