Workaround to return a list from a ComputedProperty function in NDB

元气小坏坏 提交于 2019-12-10 17:53:31

问题


I am converting my app to use NDB. I used to have something like this before:

@db.ComputedProperty
    def someComputedProperty(self, indexed=False):
      if not self.someCondition:
          return []
      src = self.someReferenceProperty
      list =  src.list1 + src.list2 + src.list3 + src.list4 \
              + [src.str1, src.str2]
      return map(lambda x:'' if not x else x.lower(), list) 

As you can see, my method of generating the list is a bit complicated, I prefer to keep it this way. But when I started converting to NDB, I just replaced @db.ComputedProperty by @model.ComputedProperty but then I got this error:

NotImplementedError: Property someComputedProperty does not support <type 'list'> types.

I could see in model.py in ext.ndb that ComputedProperty inherits from GenericProperty where in the _db_set_value there are several if/else statements that handle value according to its type, except that there's no handling for lists

Currently it goes through the first condition and gives out that error when I return an empty list.

Is there a way to work around this and avoid the error?


回答1:


You need to set the repeated=True flag for your computed property in NDB. I don't think you can use the cute "@db.ComputedProperty" notation, you'll have to say:

def _computeValue(self):
    ...same as before...
someComputedProperty = ComputedProperty(_computeValue, repeated=True, indexed=False)



回答2:


This whole functionality can be done within a function, so it doesn't need to be a ComputedProperty. Use Computed Properties only when you want to do a computation that you might query for. A ComputedProperty can have its indexed flag set to False but then this means you won't be querying for it, and therefore don't really need to have it as a property.

def someComputedProperty(self):
  if not self.someCondition:
      return []
  src = self.someReferenceProperty
  list =  src.list1 + src.list2 + src.list3 + src.list4 \
          + [src.str1, src.str2]
  return map(lambda x:'' if not x else x.lower(), list) 


来源:https://stackoverflow.com/questions/8893886/workaround-to-return-a-list-from-a-computedproperty-function-in-ndb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!