peewee python多个外键在桌子上

时间:2014-02-25 22:18:26

标签: python foreign-keys peewee

我有以下模型类:

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

如您所见,该表有多个外键。我希望能够选择所有票证并迭代它们并访问类别和事件:

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

但是,我不希望在每次迭代期间为类别和事件启动新查询。我知道,如果我刚刚访问该活动,我可以做类似的事情:

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

但是,每次访问该类别时,仍会启动新查询。这段代码给了我一个例外:

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

我得到的错误是:ValueError:类'models.ticketing.Category'和类'models.event.Event'之间没有外键

1 个答案:

答案 0 :(得分:1)

对于上一个错误:您正在尝试加入CategoryEvent,您需要切换回Ticket

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