david
david

Reputation: 6805

How do I grab the first objects from a Django queryset?

execution_list = JobExecution.objects.filter(job__name=job_name).order_by('-build_id')[:50]
last = execution_list.pop(1)
print last.id

I've also tried execution_list[0], which throws another queryset error.

How do I i just grab the first object from the queryset? I am aware that I can just append .last() to the query, but the problem is I need the full list as well as the first item. What am I doing wrong here?

Error: 'QuerySet' object has no attribute 'pop'

Upvotes: 1

Views: 8045

Answers (3)

Alasdair
Alasdair

Reputation: 309129

You can convert the queryset to a list and then pop the last item.

execution_list = list(JobExecution.objects.filter(job__name=job_name).order_by('-build_id')[:50])
last = execution_list.pop(0)

Note that I’ve used pop(0) to get the first item from the list - pop(1) would pop the second item from the list because lists are zero-indexed.

Upvotes: 0

wpercy
wpercy

Reputation: 10090

You can use .first()

For example

JobExecution.objects.filter(job__name=job_name).order_by('-build_id').first()

will return the JobExecution object with the largest build_id

Note that you can't slice and then also grab the .first() because this doesn't convert nicely into SQL, but you can do something like

queryset = JobExecution.objects.filter(job__name=job_name).order_by('-build_id')
first_50 = queryset[:50] # this will not evaluate the queryset
first = queryset.first() # this will evaluate the queryset

Upvotes: 2

Aaron Klein
Aaron Klein

Reputation: 604

Even when you slice [:50], it still returns a QuerySet rather than a list. You could say last = list(execution_list)[0], which would give you just the first element. Be aware that this would also execute the query immediately.

Upvotes: 0

Related Questions