Python peewee 外键

标签 python foreign-keys peewee

如果我有下表:

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

然后我执行下面的代码:

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

     print ticket.event.id

访问外部对象的主键是否会强制 peewee 启动另一个查询?或者 peewee 是否足够聪明,知道该 ID 已经可用?

最佳答案

几年过去了,但对于偶然发现此页面的其他人来说,现在您可以使用 Django 使用的相同语法:<>_id 来访问 id。在这种情况下,ticket.event_id。

根据 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:

然而,值得注意的是,这仅在访问查询对象的值时有效。换句话说,如果您想更改事件 ID,只需设置

ticket.event = new_event_id

而不是尝试设置 ticket.event_id。

尝试基于外键进行选择时也是如此:

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

关于Python peewee 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22017699/

相关文章:

python - 计算排列列表中的周期

python - 在不创建菜单项的情况下为功能分配快捷方式

c# - Linq to Sql 如何获取一个实体的所有外键字段

python - 如何在 Union peewee orm 中对 SQL 结果进行排序

Python#截图失败

javascript - 使用 Python 2.7 抓取/解析投注赔率

ruby-on-rails - Rails 外键验证

mysql - 为 MySQL 中的 perfromant 连接键入在两个属性上唯一的表的最佳方法?

python - 在 peewee (Flask) 的查询中包含 OneToMany 关系

python - 如何用peewee选择记录