Google App Engine中的一对多数据库设置

时间:2011-02-21 17:57:05

标签: google-app-engine google-cloud-datastore gqlquery

class Student(db.Model):
    teacher = db.ReferenceProperty(Teacher, collection_name='students')
    name = db.StringProperty(required=True)
    zip_code = db.IntegerProperty(required=True)
    square_footage = db.IntegerProperty(required=True)
    month_entries = db.IntegerProperty(required=True)  

class Bill(db.Model):
    student = db.ReferenceProperty(Student, collection_name='bills')
    bill_month = db.DateProperty(required=True)
    energy = db.IntegerProperty(required=True)

从我上面显示的模型设置中......我可以使用以下内容轻松显示所有存储的帐单:

bill = models.Bill.all()
for stubs in bill:
    print stubs.energy
    print stubs.student.name

但我如何列出每个学生的账单? 在SQL中我会说:

SELECT * FROM Bill WHERE Student.Name = Samuel

我想我不明白如何检索ReferenceProperty给出的Bills。它在GQL中似乎并不那么简单。如何通过参考属性查询?

3 个答案:

答案 0 :(得分:3)

ReferenceProperty在引用的实体中创建一个自动查询(如果你提供了一个,则使用collection_name):

sams_bills = Student.all().filter("name =", "Samuel").get().bills

sams_bills现在是账单的db.Query,您可以调用.fetch()来检索一个或多个账单。

答案 1 :(得分:1)

对于拥有SQL经验的人来说,了解App Engine最困难的事情是,很多东西需要两个查询来获得你想要的结果。

student = Student.all().filter('name =', 'Samuel').get()
bill = Bill.all().filter('student =', student.key()).get()

对于拥有SQL经验的人来说,第二个最困难的事情是几乎没有人使用GQL。 ;)

答案 2 :(得分:0)

Bill类中db.ReferenceProperty“student”的collection_name参数已经为您设置了查询。所以你要做的就是:

student = Student.all().filter('name =', 'Samuel').get()
for bill in student.bills:
    logging.info('Student %s Month:%s Energy:%d' % (student.name, str(bill.bill_month), bill.energy)

现在,反向引用查询返回的结果是无序的。您可以(如果您已正确设置索引)使用.order()以特定顺序返回它们,或者您可以将它们放入Set中并在内存中排序(非常快),如下所示:

sorted_bills = []
for bill in student.bills:
    sorted_bills.append(bill)

# Sort additions by month then by amount (secondary key sorts first in code)
sorted_bills = sorted(sorted_bills, key=lambda Bill: Bill.energy, reverse=True)
sorted_bills = sorted(sorted_bills, key=lambda Bill: Bill.bill_month, reverse=False)

在此示例中,如果学生有多个具有相同bill_month值的帐单,则最大的帐单将首先排序(请注意reverse = True参数)。

相关问题