[Django]-Get first object from Django queryset

3👍

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

randomItem = randomItemQS[0]

1👍

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

0👍

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.

Leave a comment