Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time

后端 未结 7 868
庸人自扰
庸人自扰 2020-11-30 01:25

In a Python Google App Engine app I\'m writing, I have an entity stored in the datastore that I need to retrieve, make an exact copy of it (with the exception of the key), a

相关标签:
7条回答
  • 2020-11-30 01:56

    A variation inspired in Nick's answer which handles the case in which your entity has a (repeated) StructuredProperty, where the StructuredProperty itself has ComputedProperties. It can probably be written more tersely with dict comprehension somehow, but here is the longer version that worked for me:

    def removeComputedProps(klass,oldDicc):
      dicc = {}
      for key,propertType in klass._properties.iteritems():
          if type(propertType) is ndb.StructuredProperty:
              purged = []
              for item in oldDicc[key]:
                  purged.append(removeComputedProps(propertType._modelclass,item))
              dicc[key]=purged
          else:
              if type(propertType) is not ndb.ComputedProperty:
                  dicc[key] = oldDicc[key]
      return dicc
    
    def cloneEntity(entity):
      oldDicc = entity.to_dict() 
      klass = entity.__class__
      dicc = removeComputedProps(klass,oldDicc)
      return klass(**dicc)
    
    0 讨论(0)
提交回复
热议问题