假装我有这个Django模型:
class Person(models.Model)
name = models.CharField()
age = models.IntegerField()
然后我在模型上执行以下查询:
queryset = Person.objects.filter(name="Joe").only("name") # Notice that I want to only select the name field.
object_list = list(queryset) # Purposefully triggered the database hit by calling list on it.
如何阻止执行此操作?:
object_list[0].age # accessing a field that I did not include in the "only" method triggers an additional hit to the database.
我希望它引发Exception或什么也不做,而不是第二次访问数据库。
更新:我已经回答了我自己的问题,但是我希望其他人发表他们的答案,看看他们是否有更好的解决方案。