【问题标题】:How do I know if ndb.Model.get_or_insert created a new entity or got an existing one?我如何知道 ndb.Model.get_or_insert 是创建了新实体还是获得了现有实体?
【发布时间】:2013-01-10 14:51:40
【问题描述】:

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

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

【问题讨论】:

    标签: python google-app-engine app-engine-ndb


    【解决方案1】:

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

    @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.transactional上方不应该有@classmethod吗?谢谢
    • @Hooman,如果你在一个类中使用它,那么可以,但是在它当前的函数形式中,你可以将它与任何Model 类一起使用,方法是将类作为第一个参数传递.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多