python - 在查询字典中包含连接的表列

标签 python peewee

我正在使用 peewee 查询数据库,并使用 .dicts() 返回查询,但对于ForeignKeyFields,我不知道如何在结果字典中包含外键。

代码胜于 Eloquent :

from peewee import Model

class Foo:
    name = SomeField(unique=True)

class Bar:
    param_one = SomeField()
    param_two = SomeField()
    param_xyz = SomeField()
    a_foo = ForeignKeyField(Foo)

query = Bar.select().join(Foo).dicts()
for i in query:
   print(i['a_foo'].name)
   >> AttributeError

query = Bar.select(Bar.param_one, Foo.name).join(Foo).dicts()
for i in query:
   print(i)
   >>> {'param_one': x, 'name': y}

我想知道是否有一种方法可以执行与第二个查询类似的操作,但不必在 Bar 中键入所有列名称。

即输出一个字典,其中包含 Bar 中的所有列以及 Foo 中的连接列。

最佳答案

您可以使用简写来选择模型中的所有列:

query = Bar.select(Bar, Foo).join(Foo).dicts()

使用字典时,Bar 和 Foo 中的所有字段都存在于行字典中。如果 Foo 的字段与 Bar 中的字段同名,则 Foo 中的字段将不会被包含在内,因为它会覆盖 Bar 中的字段。

关于python - 在查询字典中包含连接的表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120070/

相关文章:

python - 如何用peewee选择记录

python - 尿尿 : how to filter data in a table based on values across rows in another table

python - 使用 Python3 多处理时,是否有正确的 peewee 设置以避免 mysql 同步问题?

python - peewee 和 peewee 异步 : why is async slower

sql - 属性错误: 'bool' object has no attribute 'clone' in Peewee with SQLite

javascript - 正则表达式反向引用的结果正确吗?

Python 3 将范围转换为列表

python - 如何在 marqo 中添加搜索文档

python - 如何在 TensorFlow 中调试 NaN 值?

python - NumPy 的 : How to convert an array type quickly