我正在使用 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/