Arne Wolframm Arne Wolframm - 1 month ago 8x
Python Question

App Engine NDB Datastore Property Subclasses - Float OR Integer

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)
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()


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.


Eventually I found that the following works best:

class NumberProperty(ndb.GenericProperty):
    def _validate(self, value):
        assert isinstance(value, (int, long, float))
        return value