1
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 给出的账单。在 GQL 中似乎并不那么简单。如何按参考属性查询?

4

3 回答 3

3

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

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

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

于 2011-02-21T18:32:34.010 回答
1

我认为对于有 SQL 经验的人来说,最难理解 App Engine 是很多东西需要两个查询才能得到你想要的结果。

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

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

于 2011-02-21T18:31:46.880 回答
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 参数)。

于 2011-04-04T06:10:45.397 回答