Django filter-save QuerySet
<p>I've a django model:-</p>

<pre><code>class ModelA(models.Model):
    flag = models.BooleanField(default=True)
</code></pre>

<p>Next, I query it:- </p>

<p><code>obj = ModelA.objects.filter(flag=True)</code></p>

<p>Now, I change the <code>flag</code> of first object.</p>

<pre><code>obj1 = obj[0]
obj1.flag = False
obj1.save()
</code></pre>

<p>Now, when I get <code>obj[0]</code> again, it returns me the <code>2nd object</code> of the filtered query. <strong>Why?</strong></p>

<p>I believe that every time you run <code>obj[0]</code>, Django goes back to the database and runs the query. You can see the queries that are executed by using <code>django.db.connection</code>:</p>

<pre><code>&gt;&gt;&gt; from django.db import connection

&gt;&gt;&gt; obj = ModelA.objects.filter(flag=True)
&gt;&gt;&gt; print(connection.queries)
[]

&gt;&gt;&gt; o = obj[0]
&gt;&gt;&gt; print(connection.queries)
[{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}]

&gt;&gt;&gt; o.flag = False
&gt;&gt;&gt; o.save()
&gt;&gt;&gt; print(connection.queries)
[{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'},
 {'time': '0.000', 'sql': 'BEGIN'},
 {'time': '0.002', 'sql': 'UPDATE "myapp_modela" SET "flag" = 0 WHERE "myapp_modela"."id" = 1'}]

&gt;&gt;&gt; o = obj[0]
&gt;&gt;&gt; print(connection.queries)
[{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'},
 {'time': '0.000', 'sql': 'BEGIN'},
 {'time': '0.002', 'sql': 'UPDATE "myapp_modela" SET "flag" = 0 WHERE "myapp_modela"."id" = 1'},
 {'time': '0.000', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}]
</code></pre>

python django django-queryset