Search code examples
pythongoogle-app-enginewebapp2

fetching by foreign key elements in appengine datastore


I have three database tables:

class Book(bd.Model):
    title = db.StringProperty()
    pub_time = db.DateTimeProperty()
    subject = db.StringProperty()

class Author(db.Model):
    name = db.StringProperty()
    age = db.IntegerProperty()

class Match(db.Model):
    bk = ReferenceProperty(Book, collection_name='book')
    ath = ReferenceProperty(Author, collection_name='books_written')

Problem: I want to filter books written by an author ATH, on subject SUB

My Approach:

class BookSearch(webapp2.requestHandler):
    def post(self):
        b = Books.all().filter("subject =", 'SUB')
        a = Author.all().filter("name =", "ATH")
        ret = Match.all().filter("bk =", b). filter("ath =", a)
        self.response.out.write(ret.count())

But this does not work and i get an error:

BadValueError: Unsupported type for property  : <class 'google.appengine.ext.db.Query'>

Solution

  • a and b are queries and not entities. you need to get the entity first before you can use it as filter in another query:

    class BookSearch(webapp2.requestHandler):
        def post(self):
            b = Books.all().filter("subject =", 'SUB').get()
            a = Author.all().filter("name =", "ATH").get()
            ret = Match.all().filter("bk =", b).filter("ath =", a)
            self.response.out.write(ret.count())