Matthew Calabresi
Matthew Calabresi

Reputation: 487

Get first object from Django queryset

Given the following code:

randomItemQS = Item.objects.filter().exclude(id__in=[o.id for o in collection]).order_by('?')
randomItem = randomItemQS[:1]
calculation = randomItem.method() / constant

How can I ensure that randomItem is an Item and not a QuerySet?

If I run the code from manage.py shell, then I get the expected result. However, running this code from a view results in the AttributeError 'QuerySet' object has no attribute 'method', and indicates that the error happens on the final line.

What am I missing?

EDIT: Sorry, I should be more specific -- I have this working just fine in the shell, but it's not working in the view. What would be different?

Upvotes: 3

Views: 3541

Answers (3)

Matthew Calabresi
Matthew Calabresi

Reputation: 487

As the question was regarding the difference between a view and a shell window, the correct answer is to convert parameters passed to the view to an integer to ensure the query returns objects as expected.

Other answers have been upvoted accordingly as they are valid. Thanks.

Upvotes: 0

karthikr
karthikr

Reputation: 99680

You can do this:

randomItem=None
randomItemQS = Item.objects.filter().exclude(id__in=[o.id for o in collection]).order_by('?')[:1]
if randomItemQS:
   randomItem = randomItemQS[0]
   calculation = randomItem.method() / constant

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62968

Just index it, slicing adds a LIMIT query to the QS without executing it:

randomItem = randomItemQS[0]

Upvotes: 3

Related Questions