Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Paul Finch
5,484 PointsA peewee query
Here is my data model
from peewee import *
database = SqliteDatabase("sounds.sqlite")
class Publisher(Model):
name = CharField(unique=True)
class Meta:
database = database
class Artist(Model):
name = CharField(unique=True)
class Meta:
database = database
class Album(Model):
artist = ForeignKeyField(Artist, related_name="artist_name")
title = CharField()
release_date = DateTimeField()
publisher = ForeignKeyField(Publisher, related_name="publisher_name")
media_type = CharField()
class Meta:
database = database
and here is my query
from models import *
query = (Album
.select()
.join(Publisher)
.join(Artist)
.where(Album.title == 'Once Upon A Time'))
for disk in query:
print disk.title, disk.publisher.name, disk.artist.name
Trying to return the title along with the publisher and the artist. This throws the following error
File "C:/Users/*********/PycharmProjects/PeeWeeTest/core.py", line 25, in <module>
.join(Artist)
File "C:\Python27\lib\site-packages\peewee.py", line 383, in inner
func(clone, *args, **kwargs)
File "C:\Python27\lib\site-packages\peewee.py", line 2739, in join
raise ValueError('A join condition must be specified.')
ValueError: A join condition must be specified.
How do i create this sort of query across the three tables?
Brian Anstett
5,831 PointsBrian Anstett
5,831 PointsHey Paul, I had this EXACT same problem. I found the answer on the peewee doc pages. I looks like when you use the join() function, peewee will use the last joined table as the new source table for the next join. So for example, after you join Album with Publisher using the foreign key, an error occurs with the next join between Publisher and Artist because there there is no relationship between Publisher and Artist.
The solution is to use the switch() function to switch back to the original table after the first join with Publish, before the second join with Artist.
So the query you would want would be... query = (Album .select() .join(Publisher) .switch(Album) .join(Artist) .where(Album.title == 'Once Upon A Time'))
http://docs.peewee-orm.com/en/latest/peewee/querying.html?highlight=peewee.join#joining-on-multiple-tables.