Suat Atan PhD
Suat Atan PhD

Reputation: 1382

Google app engine string to entity

I want convert any string to my existing Entiy. Is it possible writing a convertToEntity() function as below?

class Personel(db.Model):
  name=db.StringProperty()


class IsEntityExists(webapp.RequestHandler):
  def get(self):
    entity="Personal"
    Entity=entity.convertToEntity()
    Entity.all()

Upvotes: 1

Views: 98

Answers (2)

Guido van Rossum
Guido van Rossum

Reputation: 16890

I wonder if the question is just asking to somehow look up the model class given its name, when it has already been imported. You can do this easily (but only when it has already been imported!), as follows:

cls = db.class_for_kind("Personel")
... cls.all() ...

The equivalent in NDB:

cls = ndb.Model._kind_map["Personel"]
... cls.query() ...

Good luck!

PS. No, it won't do spell correction. :-)

Upvotes: 1

vertazzar
vertazzar

Reputation: 1053

Only if you build loader for models... for example:

from app import model_loader

class IsEntityExists(webapp.RequestHandler):
  def get(self):
    Entity=model_loader("Personal")
    Entity.all()

while the model_loader function would search the folder structure (python modules) for defined model.. for example you have folder structure:

models/
personal.py
other_model.py
user.py

So the model_loader("Personal") would import personal.py and extract "Personal" class from that module, allowing you to perform whatever you want with that class - if it finds it and loads it.

Of course you would have to code the loader.

However if the class (defined model) is in the same file as the code, you could search over locals() for "Personal"

def load_model(name):
    local = locals()
    try:
      return local[name]
    except KeyError:
      return None

Upvotes: 0

Related Questions