Search code examples
pythonforeign-keyspeewee

peewee python multiple foreign keys on table


I have the following model class:

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

As you can see, the table has multiple foreign keys. I want to be able to then select all tickets and iterate over them and access both the category and event:

tickets = Ticket.select()
for ticket in tickets:
    print ticket.category.id
    print ticket.event.id

However, I don't want new queries to be launched during each iteration for the category and the event. I know that if I were just accessing the event I could do something like:

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

However, a new query will still be launched every time I access the category. This code gives me an exception:

tickets = Ticket.select(Ticket, Category, Event).join(Event).join(Category)

The error I get is: ValueError: No foreign key between class 'models.ticketing.Category' and class 'models.event.Event'


Solution

  • For the last error: you're trying to join Category to Event, you need to switch back to the Ticket:

    tickets = Ticket.select(Ticket, Category, Event).join(Event).switch(Ticket).join(Category)