通过属性变量更新 QuerySet
Update QuerySet by attribute variable
以我下面的数据为例,其中 prop
是我要更新的查询集,results
是信息字典。这个 dict 有键是这个查询集中的属性,也有键不是这个 QuerySet 中的属性。如果它的属性匹配,我只想更新这个 QuerySet...
prop = Property.objects.get(pk=14)
results = {'price': '525000', 'code': '55285', 'estimate': '1500'}
我知道这行不通,因为它需要一个字面上名为 'apicall' 的属性,但这是我希望实现的逻辑:
for apicall in results:
if hasattr(prop,apicall):
prop.apicall = results[apicall]
prop.save()
如果查询集中存在,我如何避免直接调用 prop.apicall
而改为 prop.price
?
您可以使用 setattr(…)
builtin function [python-doc],因此可以使用:
for apicall in results:
if hasattr(prop,apicall):
<strong>setattr(</strong>prop, apicall<strong>, results[apicall])</strong>
prop.save()
最好在prop
所有更改后保存,否则我们将执行大量额外的数据库查询。
以我下面的数据为例,其中 prop
是我要更新的查询集,results
是信息字典。这个 dict 有键是这个查询集中的属性,也有键不是这个 QuerySet 中的属性。如果它的属性匹配,我只想更新这个 QuerySet...
prop = Property.objects.get(pk=14)
results = {'price': '525000', 'code': '55285', 'estimate': '1500'}
我知道这行不通,因为它需要一个字面上名为 'apicall' 的属性,但这是我希望实现的逻辑:
for apicall in results:
if hasattr(prop,apicall):
prop.apicall = results[apicall]
prop.save()
如果查询集中存在,我如何避免直接调用 prop.apicall
而改为 prop.price
?
您可以使用 setattr(…)
builtin function [python-doc],因此可以使用:
for apicall in results:
if hasattr(prop,apicall):
<strong>setattr(</strong>prop, apicall<strong>, results[apicall])</strong>
prop.save()
最好在prop
所有更改后保存,否则我们将执行大量额外的数据库查询。