Workaround to return a list from a ComputedProperty function in NDB
문제
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?
해결책 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)
다른 팁
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)