英文:
Build a dictionary from an object's explicitly declared fields
问题
以下是代码部分的中文翻译:
我的表定义:
class AppProperties(base):
__tablename__ = "app_properties"
key = Column(String, primary_key=True, unique=True)
value = Column(String)
用于更新应用程序属性的代码:
session = Session()
query = session.query(AppProperties).filter(AppProperties.key == "memory")
new_setting = AppProperties(key="memory", value="1 GB")
query.update(new_setting)
`query.update(new_setting)` 这行失败是因为 update 方法需要一个可迭代对象。
如果我使用 `query.update(vars(new_setting))`,它会包含一些额外的值,这些值在底层表中并不存在,因此失败。
我如何构建这个字典:`{"key": "memory", "value": "1 GB"}`,使用对象 `new_setting`,以便我可以使用这个字典来调用 `update` 方法?
例如:
query.update({"key": "memory", "value": "1 GB"})
因为我已经在 `new_setting` 中拥有所有内容,我只需要将它转换成一个字典,其中只包含在 `AppProperties` 类定义中显式声明的那些键,而不会继承来自基类或任何其他范围的字段。
英文:
My table definition:
class AppProperties(base):
__tablename__ = "app_properties"
key = Column(String, primary_key=True, unique=True)
value = Column(String)
Code for updating an app property:
session = Session()
query = session.query(AppProperties).filter(AppProperties.key == "memory")
new_setting = AppProperties(key="memory", value="1 GB")
query.update(new_setting)
The line query.update(new_setting)
fails because the update method requires an iterable.
If I use query.update(vars(new_setting))
, it includes some extra values, which are not there in the underlying table and hence fails.
How can I build this dictionary: {"key": "memory", "value": "1 GB"}
using the object new_setting
, so that I can call the update
method using this dictionary?
For example:
query.update({"key": "memory", "value": "1 GB"})
Because I already have everything in new_setting
, I just need to convert it into a dictionary with only those keys which are explicitly declared in the class definition of AppProperties
, without inheriting the fields from the base class or any other scope.
答案1
得分: 1
为什么需要new_setting
?直接将新数据传递给update
方法即可。
英文:
Why do you need new_setting
? Just pass the new data directly to the update
method.
session = Session()
query = session
.query(AppProperties)
.filter(AppProperties.key == "memory")
.update({ 'key': 'memory', 'value': '1 GB' })
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论