Python peewee加入了多个表

时间:2014-02-25 14:14:57

标签: python join foreign-keys peewee

我希望能够在peewee中加入多个表格。然而,这个场景对于我弄清楚如何使它与peewee一起工作有点困难。

我有以下表格:

票务 TicketCategory TicketBooking 事件

以下是我的模特:

class TicketCategory(BaseModel):
    venue_id = IntegerField()
    name = CharField()
    description = CharField()

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

class TicketBooking(BaseModel):
    user_id = IntegerField()
    ticket = ForeignKeyField(Ticket, related_name="ticketbookings")
    price_paid = DecimalField()
    created = DateTimeField()
    deleted = DateTimeField()

class Event(BaseModel):
    venue_id = IntegerField()
    date = DateField()
    event_image_url = CharField()
    start = TimeField()
    end = TimeField()

现在我想运行一个查询,它将为给定用户选择所有的票务单。运行我的连接后,我希望加载所有信息 - 我不希望在访问ticketbooking.ticket.category.name或ticketbooking.ticket.event.description

时启动另一个查询

我不能这样做:

return TicketBooking.select(TicketBooking, Ticket, TicketCategory, Event).join(Ticket).join(TicketCategory).join(Event).where(
        TicketBooking.user_id == user_id,
        TicketBooking.deleted >> None
)

因为Event不是TicketCategory上的外键,所以我收到错误。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:22)

再次尝试回答这个问题。

(TicketBooking
 .select(
     TicketBooking, 
     Ticket, 
     TicketCategory, 
     Event)
 .join(Ticket)
 .join(TicketCategory)
 .join(Event)
 .where(
     TicketBooking.user_id == user_id,
     TicketBooking.deleted >> None
 ))

你快到了。请尝试改为:

(TicketBooking
 .select(
     TicketBooking, 
     Ticket, 
     TicketCategory, 
     Event)
 .join(Ticket)
 .join(TicketCategory)
 .switch(Ticket)  # <-- switch the "query context" back to ticket.
 .join(Event)
 .where(
     TicketBooking.user_id == user_id,
     TicketBooking.deleted >> None
 ))

答案 1 :(得分:1)

尝试.join(Event, on=(TicketCategory.venue_id == Event.venue_id))