简体   繁体   English

Python peewee外键

[英]Python peewee foreign keys

If I have the following table: 如果我有下表:

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

Then I execute the following code: 然后我执行以下代码:

tickets = Ticket.select()
for ticket in tickets:

     print ticket.event.id

Does accessing the primary key of the foreign object force peewee to launch another query? 访问外来对象的主键是否强制peewee启动另一个查询? Or is peewee smart enough to know that the id is already available? 或者peewee足够聪明,知道id已经可用了吗?

It executes another query. 它执行另一个查询。 To avoid this: 为了避免这种情况

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

http://peewee.readthedocs.org/en/latest/peewee/querying.html#saving-queries-by-selecting-related-models http://peewee.readthedocs.org/en/latest/peewee/querying.html#saving-queries-by-selecting-related-models

It's a few years later, but for anyone else who stumbles across this page, these days you can use the same syntax that Django uses: <<field_name>>_id to access the id. 这是几年之后,但对于偶然发现这个页面的其他人来说,这些天你可以使用Django使用的相同语法:<< field_name >> _ id来访问id。 In this case, ticket.event_id. 在这种情况下,ticket.event_id。

Per the docs : 根据文档

Sometimes you only need the associated primary key value from the foreign key column. 有时,您只需要来自外键列的关联主键值。 In this case, Peewee follows the convention established by Django, of allowing you to access the raw foreign key value by appending "_id" to the foreign key field's name: 在这种情况下,Peewee遵循Django建立的约定,允许您通过将“_id”附加到外键字段的名称来访问原始外键值:

It is, however, worth noting that this only works when accessing the value of a queried object. 但是,值得注意的是,这仅在访问查询对象的值时才有效。 In other words, if you wanted to change the event id, just set 换句话说,如果您想更改事件ID,只需设置即可

ticket.event = new_event_id ticket.event = new_event_id

instead of trying to set ticket.event_id. 而不是尝试设置ticket.event_id。

The same holds true when trying to select based off a foreign key: 尝试基于外键选择时也是如此:

Ticket.select().where(event == desired_event_id) Ticket.select()。where(event == desired_event_id)

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

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