Django `assertNumQueries` showing duplicate queries on deferred field

Viewed 207

I am having a strange behaviour that I cannot find out why it's happening. I have a simple queryset with a deferred field, for example Person.objects.filter(id=4).defer('phone') and then I have a test that asserts this:

with self.assertNumQueries(2):
   p = Person.objects.filter(id=4).defer('phone').first() # 1 query
   p.phone # 1 query

It fails, because it seems to run three queries on that block: the first one when filtering, and two more duplicate queries that come from the p.phone statement (SELECT phone FROM ...).

Does anyone have any idea why this is happening?

  • Note: i'm using Django 2.0. And it also happens using only(), the counterpart of defer().
1 Answers

I can't reproduce, it's something related to your case. I wrote this test case with default Django user that passes. Provide more info if you need a better answer.

class TestDefer(APITestCase):
    def test_defer(self):
        u = User.objects.create(email='aaa@bbb.com', is_staff=True)
        with self.assertNumQueries(1):
            p = User.objects.defer('is_staff').get(id=u.id)
        with self.assertNumQueries(1):
            print(p.is_staff)

        with self.assertNumQueries(1):
            p = User.objects.defer('email').get(id=u.id)
        with self.assertNumQueries(1):
            print(p.email)
Related