Eventually I found that the following works best:
class NumberProperty(ndb.GenericProperty):
def _validate(self, value):
assert isinstance(value, (int, long, float))
return value
Вопрос
I am trying to create an NDB property subclass that allows me to store a Number as either an ndb.IntegerProperty (if the Number is an int) or as an ndb.FloatProperty (if the Number is a float).
class Integer(ndb.Model):
number = ndb.IntegerProperty()
class Real(ndb.Model):
number = ndb.FloatProperty()
class NumberProperty(ndb.StructuredProperty):
def _validate(self, value):
assert isinstance(value, (int, float))
def _to_base_type(self, value):
if isinstance(value, int):
return Integer(number=value)
else:
return Real(number=value)
def _from_base_type(self, value):
return value.number
Then I create a test class that uses this NumberProperty and try to create an entity:
class MyNumber(ndb.Model):
value = NumberProperty()
MyNumber(value=12)
I receive the following TypeError: init() takes at least 2 arguments (1 given).
Please give me a hint how I should set up the required subclass. I tried many other forms, but nothing that works. Thanks.
Решение 2
Eventually I found that the following works best:
class NumberProperty(ndb.GenericProperty):
def _validate(self, value):
assert isinstance(value, (int, long, float))
return value
Другие советы
Try something like this:
class NumberModel(ndb.Model):
i = ndb.IntegerProperty()
f = ndb.FloatProperty()
class NumberProperty(ndb.StructuredProperty):
def _validate(self, value):
assert isinstance(value, (int, float))
def _to_base_type(self, value):
if isinstance(value, int):
return NumberModel(i=value)
else:
return NumberModel(f=value)
def _from_base_type(self, value):
v = value.i if value.i is not None else value.f
return v
https://developers.google.com/appengine/docs/python/ndb/subclassprop