简体   繁体   English

如何在Peewee ORM中选择和限制related_name连接?

[英]How to select and limit the related_name connection in the Peewee ORM?

I'm using Flask with the Peewee ORM in which I have defined two tables like so: 我将Flask与Peewee ORM结合使用,在其中定义了两个表,如下所示:

class Ticket(db.Model):
    created = DateTimeField(default=datetime.now)
    customer_uuid = CharField() # the customer's UUID gotten from App. More info comes from bunq API.
    ticket_type = ForeignKeyField(TicketType, related_name='tickets')
    active = BooleanField(default=True)

class Assign(db.Model):
    created = DateTimeField(default=datetime.now)
    ticket = ForeignKeyField(Ticket, related_name='assigned_to')
    user = ForeignKeyField(User, related_name='assigned_tickets')

In the Assign table, several users can be assigned to a ticket, but only the last one counts (ie, if a new user gets assigned, the previous ones should be disregarded). 在“分配”表中,可以将多个用户分配给故障单,但是只有最后一个计数(即,如果分配了新用户,则应该忽略先前的用户)。 So I select the active tickets using the following: 因此,我使用以下方法选择活动票证:

open_tickets = Ticket.select().where(Ticket.active == True)

I now want to use this loop in my template. 现在,我想在模板中使用此循环。 With every iteration however, I also want to display the assigned user. 但是,在每次迭代中,我还想显示分配的用户。 But open_ticket[0].assigned_to obviously returns several assignments, and with it several users. 但是open_ticket[0].assigned_to很明显会返回几个分配,并带有几个用户。

Would anybody know how I can get the latest assigned user for every ticket within a loop? 有人知道如何在循环中为每个票证获取最新分配的用户吗?

This worked for me in Sqlite: 这在Sqlite中对我有用:

q = (Ticket
     .select(Ticket, Assign, User)
     .join(Assign)
     .join(User)
     .group_by(Ticket)
     .order_by(Ticket.id, Assign.id.desc()))

for ticket in q:
    print ticket.id, ticket.assign.user.username

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM