Posts Tagged models

GAE Q/A Externalizing Model Class Def to file

Problem:
I was tired of having all of my data models for my project in the same doc as the rest of my functional code. I wanted to move it all to a models.py file.

Resolution:
Simply create a new file and then copy/paste the datamodels into it. Remember to include the import for the google app engine data model library.
Models.py

from google.appengine.ext import db

class Thing(db.Model):
Text = db.StringProperty(multiline=True)
Author = db.UserProperty()
Created = db.DateProperty()
Ratings = db.ListProperty(db.Rating)
Tags = db.ListProperty(db.Category)

worker.py

from models import *

Further, I thought it would be sweet to actually have my models in a separate folder under my project. This fits my C# based view of the world and how i was brought up declaring classes in their own document. So New Problem.

Same as original but in a sub folder.

I found a great stackoverflow.com question/answer for this. At http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder

Briefly, It says to use do the same as above with the models but with 2 additional pieces.

First, create the folder and create a new file __init__.py. This file can remain empty but will tell python that this folder is essentially and external package and that the name should be treated similarly to a name space.

Second, Update the import statement in worker.py to

from datamodels.models import *

This works like a charm. Thanks to the stack overflow guys that worked this out. follow the link and up the question/answer pair if you found this article useful.

Thanks,

John.

Leave a Comment