MHS
MHS

Reputation: 2350

Python -- How to get Oldest date from a QuerySet?

I have a QuerySet like this:

qs = [<book: OliverTwist_Mon Dec  9 00:00:00 2013>, <book: OliverTwist_Sun Sep 15 00:00:00 2013>, <book: OliverTwist_Wed May  1 00:00:00 2013>]
v_dict = qs.values('title', 'title__name').annotate(count=Count('book'))

I get this result from it:

[{'count': 3, 'title': 1, 'title__name': u'OliverTwist'}]

I want to include the oldest datetime in my dictionary,

[{'count': 3, 'title': 1, 'title__name': u'OliverTwist', rx_datetime: u'2013-05-01 00:00:00'}]

kindly help me out!

Upvotes: 0

Views: 3009

Answers (1)

iMom0
iMom0

Reputation: 12931

You can annotate min datetime:

from django.db.models import Min
qs.values('title', 'title__name').annotate(count=Count('book'), min=Min('rx_datetime'))

It will give you something like:

[{'count': 3, 'title': 1, 'title__name': u'OliverTwist', 'min': datetime.datetime(2013,5,1,0,0,0)}]

Upvotes: 1

Related Questions