2017-01-01 00:24:40 +08:00
|
|
|
from django.core.exceptions import FieldError
|
2014-06-07 00:16:17 +08:00
|
|
|
from django.test import TestCase
|
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from .models.default_related_name import Author, Book, Editor
|
2014-06-07 00:16:17 +08:00
|
|
|
|
|
|
|
|
|
|
|
class DefaultRelatedNameTests(TestCase):
|
|
|
|
|
2016-02-26 08:08:16 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
|
|
|
cls.author = Author.objects.create(first_name='Dave', last_name='Loper')
|
|
|
|
cls.editor = Editor.objects.create(name='Test Editions', bestselling_author=cls.author)
|
|
|
|
cls.book = Book.objects.create(title='Test Book', editor=cls.editor)
|
|
|
|
cls.book.authors.add(cls.author)
|
2014-06-07 00:16:17 +08:00
|
|
|
|
|
|
|
def test_no_default_related_name(self):
|
2016-02-26 08:08:16 +08:00
|
|
|
self.assertEqual(list(self.author.editor_set.all()), [self.editor])
|
2014-06-07 00:16:17 +08:00
|
|
|
|
|
|
|
def test_default_related_name(self):
|
2016-02-26 08:08:16 +08:00
|
|
|
self.assertEqual(list(self.author.books.all()), [self.book])
|
2014-06-07 00:16:17 +08:00
|
|
|
|
2016-02-24 15:10:09 +08:00
|
|
|
def test_default_related_name_in_queryset_lookup(self):
|
|
|
|
self.assertEqual(Author.objects.get(books=self.book), self.author)
|
|
|
|
|
2017-01-01 00:24:40 +08:00
|
|
|
def test_model_name_not_available_in_queryset_lookup(self):
|
|
|
|
msg = "Cannot resolve keyword 'book' into field."
|
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
2016-02-24 15:10:09 +08:00
|
|
|
Author.objects.get(book=self.book)
|
|
|
|
|
2014-06-07 00:16:17 +08:00
|
|
|
def test_related_name_overrides_default_related_name(self):
|
2016-02-26 08:08:16 +08:00
|
|
|
self.assertEqual(list(self.editor.edited_books.all()), [self.book])
|
2014-06-07 00:16:17 +08:00
|
|
|
|
|
|
|
def test_inheritance(self):
|
2016-02-26 08:08:16 +08:00
|
|
|
# model_options is the name of the application for this test.
|
|
|
|
self.assertEqual(list(self.book.model_options_bookstores.all()), [])
|
2014-06-07 00:16:17 +08:00
|
|
|
|
2015-12-03 07:55:50 +08:00
|
|
|
def test_inheritance_with_overridden_default_related_name(self):
|
2016-02-26 08:08:16 +08:00
|
|
|
self.assertEqual(list(self.book.editor_stores.all()), [])
|