通过appengine数据存储区中的外键元素获取

时间:2012-04-14 09:11:06

标签: python google-app-engine webapp2

我有三个数据库表:

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')

问题:我想过滤作者ATH撰写的关于主题SUB

的书籍

我的方法:

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())

但这不起作用,我收到错误:

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

2 个答案:

答案 0 :(得分:1)

a和b是查询而不是实体。您需要首先获取实体,然后才能将其用作另一个查询中的过滤器:

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())

答案 1 :(得分:-1)

您应该使用bk IN代替bk =,因为b中的结果可以是多个单一值。

试试这个:

ret = Match.all().filter("bk IN", b). filter("ath IN", a)

文档在这里https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_filter