简体   繁体   中英

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? Or is peewee smart enough to know that the id is already available?

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

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. In this case, 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:

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

ticket.event = new_event_id

instead of trying to set ticket.event_id.

The same holds true when trying to select based off a foreign key:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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