Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 714
Matthew Calabresi Avatar asked May 10 '26 14:05

Matthew Calabresi


1 Answers

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

randomItem = randomItemQS[0]
like image 124
Pavel Anossov Avatar answered May 12 '26 14:05

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!