Created
November 15, 2011 11:04
-
-
Save torufurukawa/1366807 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from google.appengine.ext import db | |
class ReferenceProperty(db.ReferenceProperty): | |
"""A property that represents a many-to-one reference to another model. | |
This class has serveral enhancement on | |
google.appengine.ext.db.ReferenceProperty. | |
1. Its object returns None when referenced entity does not exist, nstead | |
of raising ReferencePropertyResolveError. | |
2. It accepts access_by_key keyward argument on instantiation. If it is | |
True, you can access key of referenced object by <propertyname>_key | |
attribute. | |
""" | |
def __init__(self, | |
reference_class=None, | |
verbose_name=None, | |
collection_name=None, | |
access_by_key=False, | |
**attrs): | |
# set this value to refer from __property_config__ method. | |
self._access_by_key = access_by_key | |
super(ReferenceProperty, self).__init__(verbose_name, **attrs) | |
def __property_config__(self, model_class, property_name): | |
"""creates _key suffixed property if self._access_by_key is True""" | |
super(ReferenceProperty, self).__property_config__(model_class, | |
property_name) | |
if self._access_by_key: | |
def get_key(self): | |
property = getattr(model_class, property_name) | |
return property.get_value_for_datastore(self) | |
setattr(model_class, "%s_key" %property_name, | |
property(get_key)) | |
def __get__(self, *args, **kw): | |
try: | |
return super(ReferenceProperty, self).__get__(*args, **kw) | |
except db.ReferencePropertyResolveError: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment