Python peewee获取上次保存的行

Python peewee获取上次保存的行,python,orm,peewee,Python,Orm,Peewee,当使用peewee及其所有属性时,有没有办法获取数据库中最后保存的行? 假设我这样做: user = User.create( email = request.json['email'], nickname = request.json['nickname'], password = request.json['password'], salt = "salt" ) 但是user.id是None,我只能获得上面指定的属性。 我可以调用select()方法,但是没

当使用peewee及其所有属性时,有没有办法获取数据库中最后保存的行? 假设我这样做:

user = User.create(
    email = request.json['email'],
    nickname = request.json['nickname'],
    password = request.json['password'],
    salt = "salt"
)
但是
user.id
None
,我只能获得上面指定的属性。 我可以调用
select()
方法,但是没有更快的方法吗

谢谢

假设ID是一个自动递增的整数(默认值),这将获取最后创建的用户

或者,如果您想获得例如上次创建的客户(用户),您可以这样写:

User.select().where(User.type == "customer").order_by(User.id.desc()).get()
class User(Model):
    id = IntegerField(primary_key=True)
    email = TextField(unique=True)
    nickname = TextField()
    password = TextField()
    salt = TextField()
如果要获取上次保存的用户,则需要添加时间戳以指示用户的保存时间


更新:


Peewee现在还支持Postgres数据库的
返回
子句。您可以在任何
插入
更新
删除
查询中添加
返回
子句。查看文档:


替代重新查询数据库的方法是:

u = User(email="..", nickname="..", password="..", salt="..")
u.save()

# at this point, peewee inserted the entry in the DB,
# and updated all relevant fields (including the ID).
# For example, you can do the following:

print "ID of last-created user: %d" % u.id

对于复杂的多线程系统,我认为这是一个更好的选择。

我猜您的
用户
模型如下所示:

User.select().where(User.type == "customer").order_by(User.id.desc()).get()
class User(Model):
    id = IntegerField(primary_key=True)
    email = TextField(unique=True)
    nickname = TextField()
    password = TextField()
    salt = TextField()
但peewee不知道如何处理自动递增字段,除非您使用其PrimaryKeyField类:

class User(Model):
    id = PrimaryKeyField()
    email = TextField(unique=True)
    nickname = TextField()
    password = TextField()
    salt = TextField()

这在我能找到的任何地方都没有记录

Peewee现在还支持
返回
(仅限postgres),可用于插入、更新和删除查询。值得一提的是,如果用户有“id”的主键字段,“id”将在创建/保存时自动填充。如果没有行,即如果表为空,则会抛出错误@你可以用try/except把它包起来,今天就到此为止!