繁体   English   中英

在 peewee ORM (python) 中获取最后一个插入 ID

[英]Get last insert ID in peewee ORM (python)

我想检索最后一个插入 ID(在第二个表中用作关系),但是,我不知道如何获取它。 我正在使用 peewee ORM。

数据库 'nest' 中的表 'readings' 有一列 'id'(int (11) auto_increment,主键)。

import time
from peewee import *

database = MySQLDatabase('nest', **{'user': 'nest'})

class Readings(BaseModel):
time = DateTimeField()

class Meta:
    db_table = 'readings'

dt = Readings.insert(time=time.strftime("%x %X"))
dt.execute();
print "Last insert id:", dt.last_insert_id(database, Readings);

最后一行是我被卡住的地方。 非常感谢你的帮助。

非常感谢您的帮助,答案很简单。 这是正确的代码:

import time
from peewee import *

database = MySQLDatabase('nest', **{'user': 'nest'})

class Readings(BaseModel):
    time = DateTimeField()

class Meta:
    db_table = 'readings'

dt = Readings.insert(time=time.strftime("%x %X"))
print "Last insert id: %i" % dt.execute()
You can direct fetch id of that insert record like below

import time
from peewee import *

database = MySQLDatabase('nest', **{'user': 'nest'})

class Readings(BaseModel):
time = DateTimeField()

class Meta:
    db_table = 'readings'

dt = Readings(time=time.strftime("%x %X"))
dt.save()

print "Last insert id:"+str(dt.id);

以防万一,您可以在插入后立即获取 id

huey = User()
huey.username = 'Huey'
huey.save()
huey.id

Python 不需要分号!

只是一个说明... InsertQuery.execute() 实际上应该返回最后一个插入 id。 如果要调用 last_insert_id(),则需要传入用于执行查询的游标。

暂无
暂无

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

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