Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
Atul Bhatia Avatar asked Aug 14 '26 10:08

Atul Bhatia


2 Answers

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)

like image 186
tddawson Avatar answered Aug 16 '26 23:08

tddawson


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

like image 42
coleifer Avatar answered Aug 17 '26 01:08

coleifer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!