[英]How to do I update rows of particular user in Flask sqlalchemy
I have a query that filter out of user data and have to update periodically if any new changes arrives我有一个过滤掉用户数据的查询,如果有任何新的变化到来,我必须定期更新
@api.route('/updateUser')
def update_user():
newUpdate = ['ABC-123', 'DCS-344', 'FDC-473','HJG-297']
name = "name1"
user = User.query.filter_by(user = name).all()
# user Ouput: ['ABC-123', 'BCD-23', 'DCS-344']
try:
for i in newUpdate:
data = User(user =name, ID=i)
rows_updated =User.query.filter_by(name=name).update(ID=i))
db.session.add(rows_updated)
db.session.commit()
print("User record updated successfully!")
except:
print("Something went wrong! - Not updated")
Present output:当前输出:
user ID
name1 ABC-123
name1 BCD-233
name1 DCS-344
name2 ABE-113
name2 BCS-776
name3 RTD-445
name3 UTR-554
Desired output:期望的输出:
user ID
name1 ABC-123
name1 BCD-233
name1 DCS-344
name1 FDC-473 *
name1 HJG-297 *
name2 ABE-113
name2 BCS-776
name3 RTD-445
name3 UTR-554
Here * is the newly updated record for the name1, when this update_user() function triggers it should update the name1 record.这里 * 是 name1 的新更新记录,当这个 update_user() 函数触发时,它应该更新 name1 记录。
Can someone help with the above code, I have tried lot of online available resources regarding updating the values but didn't find one?有人可以帮忙处理上面的代码吗,我已经尝试了很多关于更新值的在线可用资源,但没有找到? I'm still in learning stage.
我还在学习阶段。 Please do the needful.
请只做那些需要的。
Thanks,谢谢,
Why you're filtering every for loop?为什么要过滤每个 for 循环? Just check your first query for is it exits and add to session.
只需检查您的第一个查询是否退出并添加到会话中。
You can't update any row in that table because you had same name's.您无法更新该表中的任何行,因为您具有相同的名称。 How do you know which row will update?
你怎么知道哪一行会更新? Your condition just name and you had multiple same name's.
您的条件只是名称,并且您有多个相同的名称。
Without updating you can just add new users like that:无需更新,您只需添加新用户即可:
for i in newUpdate:
if i not in user:
data = User(user =name, ID=i)
db.session.add(data)
db.session.commit()
print("User record updated successfully!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.