0👍
✅
That’s how list slicing works, [:1]
means [0:1]
(from index 0 to index 1) with 1
is not included:
>>> my_list = [1, 2, 3]
>>> my_list
[1, 2, 3]
>>> my_list[:1]
[1]
>>> my_list[0:1]
[1]
SomeModel.objects.filter(pk__gte=2)[:1]
means you’re slicing a QuerySet
and the result is list of model instances.
SomeModel.objects.filter(pk__gte=2).values('name')[:1]
means you’re slicing a ValuesQuerySet
and the result is list of dictionaries.
Look at the following examples:
>>> from polls.models import Question
>>>
>>> Question.objects.all()
[<Question: q1>, <Question: q2>, <Question: q3>]
>>> Question.objects.filter(pk__gte=2) # returns QuerySet
[<Question: q2>, <Question: q3>]
>>> Question.objects.filter(pk__gte=2)[:1] # slicing a QuerySet
[<Question: q2>] # list of Question instances
>>>
>>> Question.objects.filter(pk__gte=2).values('question_text') # returns ValuesQuerySet
[{'question_text': u'q2'}, {'question_text': u'q3'}]
>>> Question.objects.filter(pk__gte=2).values('question_text')[:1] # slicing a ValuesQuerySet
[{'question_text': u'q2'}] # list of dictionaries
Note: SomeModel.objects.filter(pk=2)
would always return a QuerySet
that contains 1 object (with pk=2 in this case).
1👍
Edge,
pk(primary key) is always unique. It is one of the purposes of a primary key. This in turn will help indexing. So, I am not sure why is the second returning multiple objects in the query set.
PS: please correct me if I am wrong.
- Show fields in get all django panel
- How to mix Sum and arithmetic with Django queryset
- Using php to write into django ORM
- Twilio record outgoing browser call and store the record id in an object Django
- PythonAnywhere How to handle multiple "web workers" or processes
Source:stackexchange.com