我相信每次運行obj[0]
時,Django都會返回到數據庫並運行查詢。你可以看到,通過使用django.db.connection
執行的查詢:
>>> from django.db import connection
>>> obj = ModelA.objects.filter(flag=True)
>>> print(connection.queries)
[]
>>> o = obj[0]
>>> print(connection.queries)
[{'time': '0.001', 'sql': 'SELECT "myapp_modela"."id", "myapp_modela"."flag" FROM "myapp_modela" WHERE "myapp_modela"."flag" = 1 LIMIT 1'}]
>>> o.flag = False
>>> o.save()
>>> 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'}]
>>> o = obj[0]
>>> 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'}]
你怎麼知道它是第二個對象?你如何評價它?可能 - 這是問題,當您再次評估查詢集時,第二個對象成爲第一個匹配條件的對象? – karthikr
我'打印'它。對象的'id'。 – PythonEnthusiast
看看[首頁](https://docs.djangoproject.com/en/1.10/ref/models/querysets/#first) –