Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Looking at the IDs, it seems that when you assign an entry to a variable, you get its copy, not its original reference:</p> <pre><code>In [11]: people = People.objects.filter(salary=100) In [12]: person = people[0] In [13]: person.salary = 5000 In [14]: print person.salary 5000 In [15]: people[0].salary Out[15]: 100 In [16]: id(people[0]) Out[16]: 35312400 In [17]: id(person) Out[17]: 35313104 </code></pre> <p>So, let's look at what it happens in depth. You know that in Django QuerySets are evaluated only when you need their results (lazy evaluation). To quote <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated" rel="nofollow">the Django documentation</a>:</p> <blockquote> <p><strong>Slicing</strong>. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python’s array-slicing syntax. Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated (partially or fully) also returns a list.</p> </blockquote> <p>In particular, looking at the <a href="https://github.com/django/django/blob/master/django/db/models/query.py" rel="nofollow">'django.db.models.query' source code</a>,</p> <pre><code> def __getitem__(self, k): """ Retrieves an item or slice from the set of results. """ # some stuff here ... if isinstance(k, slice): qs = self._clone() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return k.step and list(qs)[::k.step] or qs qs = self._clone() qs.query.set_limits(k, k + 1) return list(qs)[0] </code></pre> <p>you can see that when you use <em>slicing</em>, you are calling the <code>__getitem__</code> method. Then the <code>self._clone</code> method will provide you a different instance of the same QuerySet. This is the reason you are getting different results.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload