user3148949
user3148949

Reputation: 578

Django query optimisation: Get first and latest results

I have a Report model with a created date. I want to get the first and latest reports based on created date. For example, if we have following reports with created date

    R1 (2017-02-01)
    R2 (2017-01-02)
    R3 (2017-03-01)
    R4 (2017-01-31)
    R5 (2016-01-01)
    R6 (2017-03-04)

if count=5 expected result should be [R5,R4,R1,R3,R6]

if count=3 expected result should be [R5,R3,R6]

Here is the solution I came up with.

def get_reports(client, count=5):
    first = list(Report.objects.filter(client=client).order_by('created')[:1])
    rest = list(Report.objects.filter(client=client).order_by('-created')[:count - 1])
    rest.reverse()
    if first and first[0] in rest:
        return rest
    else:
        return first + rest

It works but wants to know if there is a better way to do this.

Upvotes: 0

Views: 82

Answers (1)

albar
albar

Reputation: 3090

I think you can do only one query:

qset = Report.objects.filter(client=client).order_by('-created')
first = [ qset.last() ] 
rest = list(qset[:count - 1])

Upvotes: 2

Related Questions