Let’s say I have code:
obj = MyUser.objects.get(pk=1)
name = obj.name
age = obj.age
email = obj.email
phone = obj.phone
city = obj.city
So I have obj. Is this an array with all information about MyUser object or it is only a reference?
I’m interesting is name = obj.name sends first request to DB,
age = obj.age sends second request to DB,
email = obj.email sends third request to DB,
phone = obj.phone sends fourth request to DB,
city = obj.city sends fifth request to DB
or there is only one request, when obj = MyUser.objects.get(pk=1).
Not secret that it affects the system performance, so it it very interesting question.
Thanks!
It’s neither: it’s an object whose values are initialized from the database when it’s instantiated. Django by default does a select for the whole row, and uses the column values to instantiate the object.
Doing it the way you describe would be very odd, and extremely inefficient. And what would happen if you asked for a queryset? One query per column per row?
Of course, you can ask for only certain columns, by using
valuesorvalues_listto just get the ones you’re interested in, or by usingdeferoronlyto get an object with some of the fields deferred.Note that you can ask Django what it’s doing – in the shell, in debug mode, do
which will give you a list of all the db queries up to that point in that shell session.