我怎么知道 ndb.Model.get_or_insert 是创建了一个新实体还是获得了一个现有实体? [英] How do I know if ndb.Model.get_or_insert created a new entity or got an existing one?

查看:13
本文介绍了我怎么知道 ndb.Model.get_or_insert 是创建了一个新实体还是获得了一个现有实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下(损坏的)函数,如果实体被创建或更新,我想返回 True,否则返回 False.问题是我不知道 get_or_insert() 是获取了现有实体还是插入了实体.有没有简单的方法来确定这一点?

For the following (broken) function, I want to return True if the entity was created or updated, and False otherwise. The problem is that I do not know whether get_or_insert() got an existing entity, or inserted one. Is there an easy way to determine this?

class MyModel(ndb.Model):
    def create_or_update(key, data):
        """Returns True if entity was created or updated, False otherwise."""

        current = MyModel.get_or_insert(key, data=data)

        if(current.data != data)
            current.data = data
            return True

        return False

推荐答案

get_or_insert() 是一个微不足道的函数(虽然它的实现看起来很复杂,因为它试图处理不寻常的属性名称).您可以轻松地自己编写:

get_or_insert() is a trivial function (although its implementation looks complex, because it tries to deal with unusual property names). You can easily write it yourself:

@ndb.transactional
def my_get_or_insert(cls, id, **kwds):
  key = ndb.Key(cls, id)
  ent = key.get()
  if ent is not None:
    return (ent, False)  # False meaning "not created"
  ent = cls(**kwds)
  ent.key = key
  ent.put()
  return (ent, True)  # True meaning "created"

这篇关于我怎么知道 ndb.Model.get_or_insert 是创建了一个新实体还是获得了一个现有实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆