mFontoura mFontoura - 1 year ago 150
Python Question

Creating a App Engine Datastore entity

I'm using google app engine and I'm trying to insert a entity/table using the code:

class Tu(db.Model):
title = db.StringProperty(required=True)
presentation = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)


a = Tu('teste', 'bla bla bla bla')
a.votes = 5

but I get this error:

TypeError: Expected Model type; received teste (is str)

I'm following this doc and I don't see where I'm wrong.

Answer Source

When you create a model in that way, you need to use keyword arguments for all attributes of your model. Here is a snippet of the __init__ signature from db.Model, from which your Tu model inherits:

def __init__(self,
    """Creates a new instance of this model.

    To create a new entity, you instantiate a model and then call put(),
    which saves the entity to the datastore:

       person = Person() = 'Bret'

    You can initialize properties in the model in the constructor with keyword

       person = Person(name='Bret')

    # continues

When you say a = Tu('teste', 'bla bla bla bla'), since you aren't providing keyword arguments and are instead passing them as positional arguments, teste is assigned to the parent argument in the __init__ (and bla bla bla bla to the key_name) and since that argument needs an object of type Model (which I'm assuming you don't have), you get that error. Assuming you are instead trying to add those items as title and presentation, you would say (as @DanielRoseman already succinctly stated :) ):

a = Tu(title='teste', presentation='bla bla bla bla')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download