1

I have a model in mongoengine defined like this:

class Task(Document):

    name = StringField(required=True, unique=True)
    frequency = IntField(required=True)
    quantity = IntField()
    units = StringField()
    events = ListField(DateTimeField(default=datetime.datetime.now))

How can I get the latest event? I've tried the following to no success:

def latest(self):
    return self.events.sort()[-1]

Instead of returning the events sorted sort returns None

stoebelj
  • 1,536
  • 2
  • 14
  • 31
  • 1
    You could just use the Mongoengine SortedListField instead of ListField, [here is the doc](http://docs.mongoengine.org/apireference.html#mongoengine.fields.SortedListField) Then you could simply `return self.events` or its reverse if you wish as well – Sreenadh T C Sep 16 '17 at 18:16
  • @SreenadhTC this sounds like a good solution. If you want to write it as an answer I will accept it. – stoebelj Sep 16 '17 at 21:27

1 Answers1

2

You could just use the Mongoengine SortedListField instead of ListField, here is the doc

Then you could simply return self.events or its reverse if you wish as well

Sreenadh T C
  • 592
  • 2
  • 17