0

I have two kind like this:

class A(db.Model):
    propertyA = db.XxxProperty(required=True)

class B(db.Model):
    reference = db.ReferenceProperty(A,collection_name="Bs",required=True)
    date = db.DateTimeProperty(auto_now_add=True)

Now I want make A.Bs has order, you konw, means using B.date to order A.Bs. How can I do that? What GQL query should I write?

Thank you!

Adam Crossland
  • 14,198
  • 3
  • 44
  • 54
hakunami
  • 2,351
  • 4
  • 31
  • 50

2 Answers2

1

Try this

a.Bs.order("date")

or (for descending order):

a.Bs.order("-date")
Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87
  • In this relationship, A has a property Bs which has many B, and B has a date property. I get an A entity, when I iterate its Bs, I hope they are oedered by date. I pass the A entity to template.{%for b in a.Bs%} – hakunami May 06 '12 at 06:54
  • @stevenYANG order is immutable it won't order the Bs, you need to create a new method (ordered_bs) to A that will return self.Bs.order("date") and then {%for b in a.ordered_bs%} – Shay Erlichmen May 06 '12 at 07:18
  • Does the method need to be decorated? I have no experience to give a kind a method, is there any reference? Thank you:) – hakunami May 06 '12 at 07:21
  • @stevenYANG just a plain old method, you can decorated it with property but you don't have to. – Shay Erlichmen May 06 '12 at 07:26
0

Shay's suggestion is succinct and correct, though I think it would be helpful to add some more detail.

Using the same two class examples as in the question, I created the following class for rendering my page (GAE, python, jinja2)

class MainPage(Handler):
    def get(self):
        a_id = '1001'  # magically get id of target entity a somehow
        # get key using a_id, then retrieve entity using that
        a = db.get(db.Key.from_path('A', a_id, parent=reg_key()))
        # look up the collection and assign it to b
        b = a.Bs
        # sort items in collection in reverse
        b.order('-created')
        # pass b to the template to get rendered (I use a custom method in my Handler)
        self.render('main.html', b = b)
jcarpio
  • 3,350
  • 5
  • 23
  • 22