Search code examples
pythongoogle-app-engineobjectdereference

How to identify objects with broken reference properties in google app engine


How do you correctly check for broken reference properties in google app engine?

Example:

class User (db.Model):
    userName = db.StringProperty(multiline=False)
class Foo (db.Model):
    user = db.ReferenceProperty(User, collection_name="user_foo")
  1. A User object was created.
  2. A Foo object was created.
  3. The corresponding reference property in User was then deleted.

Solution

  • As suggested by Daniel Roseman in the comments:

    "iterate through all Foos and access item.user, and [check] if that ResolveError is raised"

    from google.appengine.api import datastore_errors
    
    all_foo = Foo.all()
    for bar in all_foo:
        try:
            user_refProperty = bar.user
        except datastore_errors.Error, e:
            if e.args[0][0:40] == "ReferenceProperty failed to be resolved:":
                bar.delete()
                self.response.out.write('deleted due to bad reference property')
            else: raise