views:

704

answers:

3

Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.

EDIT: Here is what I have unsuccessfully tried:

class Comment(db.Model):
    series = db.ReferenceProperty(reference_class=Series);

    def series_id(self):
        return self._series

And in my template:

<a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>

The result:

<a href="games/view-series.html?series=#comm59">more</a>
+1  A: 

You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.

Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.

Nick Johnson
Django doesn't allow you to access members that start with _
Chris Marasti-Georg
Ah. Well, you could always define a simple property to fetch it: "series_key = property(lambda x: x._series)", for example.
Nick Johnson
+7  A: 

Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.

However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:

class Comment(db.Model):
    series = db.ReferenceProperty(reference_class=Series);

    def series_id(self):
        return Comment.series.get_value_for_datastore(self)

When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.

A: 

I have tried your method, but I still can't implement what you have said

when I access the referenced property in the template I get nothing what's the matter

zinking