12

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

我有以下表格:

Ticket 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 上的外键,所以我得到一个错误。任何帮助将非常感激。

4

2 回答 2

24

打算再回答一次。

(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
 ))
于 2014-02-28T19:21:39.180 回答
1

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

于 2014-02-25T15:20:17.930 回答