简体   繁体   English

Python 更新数据库列有覆盖问题吗?

[英]Python updating DB column issue with overwrite?

I have a simple function which should update a certain column for certain users:我有一个简单的功能,它应该为某些用户更新特定的列:

for key, group in groupby(list_i):
    print key, type(key), len(list(group)), type(len(list(group)))
    setattr(User.query.filter_by(id=key).first(), "number_of_rooms", len(list(group)))
db_session.commit()

I have a list ( list_i ) which has the data, simply look at the print:我有一个包含数据的列表( list_i ),只需看一下打印:

在此处输入图像描述

The data is correct, the first number is the id of the user and the second is the value which should be assign to column number_of_rooms数据正确,第一个数字是用户的 ID,第二个是应该分配给列number_of_rooms的值

The problem is it sets all values of the users to 0 .问题是它将用户的所有值设置为0 I assume it is somehow an override issue of the last user, I dont know.我认为这是最后一个用户的覆盖问题,我不知道。 The thing is if I change it to:问题是如果我将其更改为:

setattr(User.query.filter_by(id=key).first(), "number_of_rooms", 2)

It will change the value to 2 for all users with id=key so the function works.对于所有具有id=key的用户,它会将值更改为2 ,以便该函数起作用。 I am here very confused, because len(list(group)) is a simple integer and it should work.我在这里很困惑,因为len(list(group))是一个简单的整数,它应该可以工作。

EDIT:编辑:

I double checked everything, I also made an other test with a variable ( t ) which increments by 1 and added an onther print to check everything, with the variable it also works, how is that possible?我仔细检查了所有内容,我还使用变量 ( t ) 进行了另一个测试,该变量以 1 递增并添加了一个打印来检查所有内容,它也可以使用变量,这怎么可能?

t = 0
for key, group in groupby(list_i):
    print key, type(key), len(list(group)), type(len(list(group)))
    my_user = User.query.filter_by(id=key).first()
    setattr(my_user, "number_of_rooms", t)
    print my_user.number_of_rooms
    t+=1
db_session.commit()

The value of number_of_rooms changes: number_of_rooms的值发生变化:

在此处输入图像描述

As Roman Mindlin and glibdud have specified, list(group) can only be used once.正如Roman Mindlinglibdud所指定的, list(group)只能使用一次。 Since group is of type <type 'itertools._grouper'> , after you iterate over group once (eg by calling list() on it), it's exhausted.由于group的类型为<type 'itertools._grouper'> ,在您迭代group一次之后(例如,通过调用list() ),它就用完了。 The key is to save the list(group) inside a variable.关键是将list(group)保存在一个变量中。

Here is the code that fixes the issue:这是解决问题的代码:

for key, group in groupby(list_i):
    l_group = list(group)
    print(l_group)
    my_user = User.query.filter_by(id=key).first()
    setattr(my_user, "number_of_rooms", len(l_group))
db_session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM