Search code examples
pythonforeign-keyspeewee

Python peewee foreign keys


If I have the following table:

class Ticket(BaseModel):
    event = ForeignKeyField(Event)
    category = ForeignKeyField(TicketCategory)
    order_number = IntegerField()
    tier_name = CharField()
    num_available = IntegerField()
   price = DecimalField()

Then I execute the following code:

tickets = Ticket.select()
for ticket in tickets:

     print ticket.event.id

Does accessing the primary key of the foreign object force peewee to launch another query? Or is peewee smart enough to know that the id is already available?


Solution

  • It executes another query. To avoid this:

    Ticket.select(Ticket, Event).join(Event)
    

    http://peewee.readthedocs.org/en/latest/peewee/querying.html#saving-queries-by-selecting-related-models