Kwame
Kwame

Reputation: 1097

How to call a function inside a gae db.Model class

I'm using appengine 1.8 with python 2.7

I have the following type of object:

class Person(db.Model):
  name = db.StringProperty()
  email = db.EmailProperty()

and the person's pictures:

class Photo(db.Model):
  image = db.BlobProperty()
  type = db.StringProperty()
  caption = db.TextProperty()
  person = db.ReferenceProperty(Person)

I would like to have a function inside the Person class that directly accesses a Person's Photos like so:

    class Person(db.Model):
     name = db.StringProperty()
     email = db.EmailProperty() 

     @property
     def photos(self):
       photos =  Photo.all().filter("person =", self._key)

However this is not working. Should I be using self._key or is there another way to access the Key for the enclosing entity?

Thanks.

Upvotes: 1

Views: 92

Answers (2)

voscausa
voscausa

Reputation: 11706

An example:

class Photo(db.Model):
    image = db.BlobProperty()
    type = db.StringProperty()
    caption = db.TextProperty()
    person = db.ReferenceProperty(Person)

    @classmethod
    photos_of_person(cls, person_key):

        return cls.all().filter("person =", person_key)

class Person(db.Model):
    name = db.StringProperty()
    email = db.EmailProperty() 

    def person_photos(self):

        return Photo.photos_of_person(self.key()) 

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

If this is your full code, you don't seem to be actually returning any value in your photos method. Rather than assigning to a local variable called photos, you actually need to return that value.

(Please ignore the inaccurate comments requesting you use a classmethod. That is obviously wrong, because you need to access the current key value, so it is an instance method, not a classmethod.)

Upvotes: 1

Related Questions