Ejemplo n.º 1
0
    def test_foreignkey_reverse(self):
        books = list(Book.objects.all())
        with self.assertNumQueries(1):
            prefetch_related_objects(books, 'first_time_authors')

        with self.assertNumQueries(0):
            [list(book.first_time_authors.all()) for book in books]
Ejemplo n.º 2
0
    def test_foreignkey_forward(self):
        authors = list(Author.objects.all())
        with self.assertNumQueries(1):
            prefetch_related_objects(authors, 'first_book')

        with self.assertNumQueries(0):
            [author.first_book for author in authors]
Ejemplo n.º 3
0
    def test_prefetch_object(self):
        book1 = Book.objects.get(id=self.book1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects([book1], Prefetch('authors'))

        with self.assertNumQueries(0):
            self.assertCountEqual(book1.authors.all(),
                                  [self.author1, self.author2, self.author3])
Ejemplo n.º 4
0
    def test_m2m_reverse(self):
        author1 = Author.objects.get(id=self.author1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects([author1], 'books')

        with self.assertNumQueries(0):
            self.assertCountEqual(author1.books.all(),
                                  [self.book1, self.book2])
Ejemplo n.º 5
0
    def test_prefetch_queryset(self):
        book1 = Book.objects.get(id=self.book1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects(
                [book1],
                Prefetch('authors',
                         queryset=Author.objects.filter(
                             id__in=[self.author1.id, self.author2.id])))

        with self.assertNumQueries(0):
            self.assertCountEqual(book1.authors.all(),
                                  [self.author1, self.author2])
Ejemplo n.º 6
0
    def test_m2m_then_m2m(self):
        """A m2m can be followed through another m2m."""
        authors = list(Author.objects.all())
        with self.assertNumQueries(2):
            prefetch_related_objects(authors, 'books__read_by')

        with self.assertNumQueries(0):
            self.assertEqual(
                [[[str(r) for r in b.read_by.all()] for b in a.books.all()]
                 for a in authors],
                [
                    [['Amy'], ['Belinda']],  # Charlotte - Poems, Jane Eyre
                    [['Amy']],  # Anne - Poems
                    [['Amy'], []],  # Emily - Poems, Wuthering Heights
                    [['Amy', 'Belinda']],  # Jane - Sense and Sense
                ])
Ejemplo n.º 7
0
 def test_unknown(self):
     book1 = Book.objects.get(id=self.book1.id)
     with self.assertRaises(AttributeError):
         prefetch_related_objects([book1], 'unknown_attribute')