Peewee getting column after join
Asked Answered
B

1

7

I am unable to read the column of another table which is joined. It throws AttributeError

class Component(Model):
  id = IntegerField(primary_key=True)
  title = CharField()

class GroupComponentMap(Model):
  group = ForeignKeyField(Component, related_name='group_fk')
  service = ForeignKeyField(Component, related_name='service_fk')

Now the query is

comp = (Component
        .select(Component, GroupComponent.group.alias('group_id'))
        .join(GroupComponent, on=(Component.id == GroupComponent.group))
       )

for row in comp:
  print row.group_id

Now I get an error AttributeError: 'Component' object has no attribute 'group_id'

Br answered 25/9, 2014 at 12:32 Comment(2)
row has attrs id and title, what do you mean by group_id?Crwth
in the select i have added GroupComponent.group.alias('group_id') so I want to get the value of group_idBr
C
8

If you just want to directly patch the group_id attribute onto the selected Component, call .naive(). This instructs peewee that you don't want to reconstruct the graph of joined models -- you just want all attributes patched onto a single Component instance:

for row in comp.naive():
    print row.group_id  # This will work now.
Crespi answered 25/9, 2014 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.