Python appengine数据存储中外键元素的获取
我有三个数据库表:Python appengine数据存储中外键元素的获取,python,google-app-engine,webapp2,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):
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'>
BadValueError:属性的类型不受支持:
您应该在中使用bk,而不是bk=
,因为b
中的结果可能不止一个值
试试这个:
ret = Match.all().filter("bk IN", b). filter("ath IN", a)
文档在这里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())
还没有尝试过,但可能会有用,还有一个问题,比如我确定只有一位作者的名字是ATH。我如何使用get
而不是filter
来写作。你不能。如果您知道密钥,您只能获取
。抱歉,但是上面的解决方案不起作用,在中应该始终附加一个列表项。然后将您的值b
和a
转换为列表?将作者=引用属性(作者)
添加到您的图书模型中不是更简单吗?这样以后你就可以做一个Book.all().filter(“subject”,“SUB”).filter(“author”,author\u key)。fetch()
?谢谢你的建议,但是,对不起@alex,但是为什么你忘了一本书可以有多个作者?一个作者可以写多本书。对,对不起,我没看到。但是,使用起来很简单:authors=ListProperty(Key)
。我想查询应该是相同的。顺便说一句,我强烈建议使用新的库NDB,它允许您执行类似于author=KeyProperty('author',repeated=True)
这是我最不想在我的项目中实现的事情,有太多的事情已经完成,我可能会在我的下一个项目中看一看。非常感谢,它救了我的命!!我想退出这个项目!!这将获取关于SUB主题的第一本书,并尝试将其与具有该名称的作者匹配,而不是按该主题显示所有书籍。要做到这一点,OP需要去掉Match
类,将authors设置为book上的listproperty,然后在此基础上进行过滤。