thosphor
thosphor

Reputation: 2781

Include joined table columns in query dicts

I'm using peewee to query a database, and I'm returning the query using .dicts(), but for ForeignKeyFields I don't know how to include the foreign key in the resulting dict.

Code speaks louder than words:

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}

I'm wondering whether there's a way to do something similar to the second query but without having to type all of the column names in Bar.

I.e., output a dictionary which includes all columns in Bar, and the joined column in Foo.

Upvotes: 0

Views: 242

Answers (1)

coleifer
coleifer

Reputation: 26245

You can use a short-hand to select all columns from a model:

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

When using dicts, all the fields from Bar and Foo are present in the row dict. If Foo has fields that share the same name as a field in Bar, then the field from Foo will not be included as it would overwrite a field from Bar.

Upvotes: 1

Related Questions