Search code examples
pythongoogle-app-enginereferenceproperty

Need help understanding ReferenceProperty


Say I have two classes:

class A(db.Model):

class B(db.Model):
    a_reference = ReferenceProperty(A)

I can now do the following:

a = A()
a.put()

b = B();
b.a_reference = a.key()

b.put()

The documentation states the following two things:

The ReferenceProperty value can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way.

And later also states:

An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists.

So what does that mean? The value is a key but it can be used a model instance?

If I do:

a2 = b.a_reference

a2 will be of type A, not key. Does this mean that the variable a_reference will behave like a model instance until that instance is deleted, whereafter it will return a key (pointing to a non-existing instance)?


Solution

  • A ReferenceProperty will always try to return an instance of the class that the stored key points to. If the referenced object has been deleted, I believe that you get back None. From the docs:

    obj1 = obj2.reference
    
    if not obj1:
        # Referenced entity was deleted.
    

    If you want to get the key that was originally stored, you can use get_value_for_datastore:

    a = A()
    a.put()
    
    b = B();
    b.a_reference = a.key()
    
    b.put()
    
    orginial_key = b.a_reference.get_value_for_datastore()