0

I have two classes declared as follows:

from mongoengine import Document, fields, DynamicDocument

class Booking(DynamicDocument):
    booking_id=fields.StringField(required=True)
    pickup_timestamp=fields.DateTimeField()

class Assignment(Document):
    created_timestamp=fields.DateTimeField(default=datetime.datetime.utcnow)
    pickup_time=fields.DateTimeField()
    bookings=fields.ListField(fields.ReferenceField(Booking))

My application allows a user to club Bookings together under an Assignment object, by selecting the Booking objects from a list on the UI. When creating the assignment object I automatically set the pickup time to the least value from the Booking pickup_timestamp like so -

assignment.pickup_time = min([booking.pickup_timestamp for booking in assignment.bookings])

However I also need to set other attributes on the assignment object based on other fields in the earliest Booking object. My question - Is there a way to sort a ListField containing ReferenceFields by a field on the referenced objects?

I did find this answer, however it does not talk about ReferenceFields in the ListField. Tried setting the field type to SortedListField as well, but I wasn't able to figure out how to specify which key to sort on.

1 Answers1

0

Solved with -

assignment.bookings=sorted(assignment.bookings, key=lambda k: k.pickup_timestamp)

Which is pretty much the same as this answer. I didn't know that the MongoEngine ListField behaves exactly like a dictionary in this regard! If there is a more efficient/better way to do this, would be very keen to know!