【问题标题】:Get last insert ID in peewee ORM (python)在peewee ORM(python)中获取最后一个插入ID
【发布时间】:2016-12-11 18:51:13
【问题描述】:

我想检索最后一个插入 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);

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

【问题讨论】:

    标签: python mysql peewee


    【解决方案1】:

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

    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()
    

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          Python 不需要分号!

          请注意... InsertQuery.execute() 实际上应该返回最后一个插入 ID。如果你想调用 last_insert_id() 你需要传入用于执行查询的游标。

          【讨论】:

          • 非常感谢 - 分号自动出现 - 我刚刚根据您的回答发布了正确的代码。
          猜你喜欢
          • 2015-03-08
          • 2023-03-16
          • 2011-04-30
          • 2011-06-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-07
          相关资源
          最近更新 更多