0

I'm developing an API with Django 1.11.11 and python 3.6.4. I have the following model:

class Subsection(models.Model):
    genres = models.ManyToManyField(Genre, blank=True, default=None)
    tags = models.ManyToManyField(Tag, blank=True, default=None)

And I'm doing the following query:

subsection = Subsection.objects.filter(**q_objects).prefetch_related('genres', 'tags').first()

So, then I can do:

genres = subsection.genres.all()
tags = subsection.tags.all()

However, this is doing new calls even the prefetch_related, what am I doing wrong?

Thanks in advance

FVod
  • 2,245
  • 5
  • 25
  • 52
  • How have you found this is running additional queries? To me this seems correct. Try to print(subsection._prefetched_objects_cache), it shouldn't be empty – Alexandr Tatarinov Mar 27 '18 at 07:07
  • I'm checking this on my tests with assuredNumQueries – FVod Mar 27 '18 at 07:16
  • Can you please provide the test and the code under the test if any? If you are testing View, maybe I know the issue – Alexandr Tatarinov Mar 27 '18 at 07:20
  • The test is just a call to the view that does the code written above: def test_numQueries(self): with self.assertNumQueries(3): self.client.get(url) – FVod Mar 27 '18 at 08:01
  • The strange thing here is even if prefetch related doesn't work, that two queries are not used and due to lazy evaluation cannot call the DB.. – Alexandr Tatarinov Mar 27 '18 at 08:11
  • Don't use the browsable API, it'll make extra query on its own to fill the dropdown for example. – Linovia Mar 27 '18 at 08:40
  • Thanks for your help. Those two queries are used in order to serialize the data, thats why the query is done; however, I don't understand why the queries are being done even the prefetch_related. Thanks a lot! – FVod Mar 27 '18 at 19:56
  • If you are using UpdateModelMixin, then take a look at it source code and you will see the reason for additional queries – Alexandr Tatarinov Mar 29 '18 at 06:31

0 Answers0