Reputation: 11309
I have the following code to try to create a message with a default value:
MESSAGE_STORE = "messages"
def get_message_key(key_name=MESSAGE_STORE):
return ndb.Key("Message", key_name)
def save_message(msg):
message = Message(parent=get_message_key(MESSAGE_STORE), message=msg)
message.put()
class Message(ndb.Model):
message = ndb.StringProperty(indexed=False)
def __init__(self, *args, **kwargs):
super(Message, self).__init__(self)
self.message = kwargs.get('message', 'No Message')
I get the error ever time, though. How can I call this properly, it works fine if I just have no constructor and call it with:
message = Message(parent=get_message_key(MESSAGE_STORE))
message.message = "Test Message"
What is with the error?
Upvotes: 1
Views: 1501
Reputation: 12986
You should not override __init__ like this, you will more than likely run into problems. ndb.Model makes heavy use of metaclasses and there is little or no value in overriding init especially in this case.
If you want a default value then define the model as follows
class Message(ndb.Model):
message = ndb.StringProperty(indexed=False, default="No Message")
As an aside you should consider making your two functions classmethods, that way you don't have remember to import the functions each time you want to fetch and save Messages. That way you only need to import the model and then use Message.save_message
etc..
Upvotes: 1
Reputation: 11309
OK, for anyone looking, the * and ** arguments need to be understood for this. This page helped:
http://freepythontips.wordpress.com/2013/08/04/args-and-kwargs-in-python-explained/
With that in mind, this seems to work properly:
MESSAGE_STORE = "messages"
def get_message_key(key_name=MESSAGE_STORE):
return ndb.Key("Message", key_name)
def save_message(msg):
message = Message(parent=get_message_key(MESSAGE_STORE), message=msg)
message.put()
class Message(ndb.Model):
message = ndb.StringProperty(indexed=False)
def __init__(self, **kwargs):
super(Message, self).__init__(**kwargs)
self.message = kwargs.get('message', 'No Message')
Upvotes: 0