从对象的明确声明字段构建一个字典。

huangapple go评论57阅读模式
英文:

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' })

...

huangapple
  • 本文由 发表于 2023年5月22日 17:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定