简体   繁体   中英

GqlQuery OrderBy a property in a ReferenceProperty

I don't know how to make a GqlQuery that order by a property of the ReferenceProperty.

In this case, I want to get all the Seat but order by the id of the Room

The GqlQuery reference does not allow a join, so how do you approach in this case?

class Room(db.Model):
    id = db.IntegerProperty()
    dimension = db.StringProperty(multiline=True)

a room has many seats, each with an id

class Seat(db.Model):
    id = db.IntegerProperty()
    roomId = db.ReferenceProperty(Room)



seats_query = GqlQuery("SELECT * FROM Seat ")
seats = seats_query.fetch(1000)

Alex is right on his point, so I decided not to touch GqlQuery, and tried to play with Django template instead, I have found the solution to sort Seat by Room'id without having to add new field in Seat class.

I put the code here if anyone has interests ;)) Cheers ;))

        {% regroup seats|dictsort:"roomId.id" by roomId.id as room_list %}
        <ul>
         {% for room in room_list %}
          <li>Room: {{room.grouper}}
            <ul>
            {% for item in room.list %}
            <li>Seat no: {{item.id}} </li>
            {% endfor %}
            </ul>
          </li>
          {% endfor %}
        </ul>

In general, to work around non-relational DBs lack of JOIN functionality, you denormalize; specifically, you redundantly put data pieces in more than one place, so they can be effectively accessed in your queries (this does make it more cumbersome to update your store, but then, non-relational DBs in general are heavily slanted to read-mostly applications).

In this case, you add to Seat a property with the room's id -- since you have peculiarly called roomId (rather than, say, room ) the reference to the seat's room, I guess you'd have this denormalized bit as roomIdId .

I think in you case it will work as you want:

class Seat(db.Model):
    id = db.IntegerProperty()
    roomId = db.ReferenceProperty(Room,collection_name='seats')

And after that you may use something like this:

rooms = Room.all().order('id')
for room in rooms:
    seat_at_room = room.seats.order('id')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM