Arne Wolframm Arne Wolframm - 1 year ago 133
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.

Answer Source

Eventually I found that the following works best:

class NumberProperty(ndb.GenericProperty):
    def _validate(self, value):
        assert isinstance(value, (int, long, float))
        return value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download