|
1 from django.test import TestCase |
|
2 |
|
3 from models import Person, Book, Car, PersonManager, PublishedBookManager |
|
4 |
|
5 |
|
6 class CustomManagerTests(TestCase): |
|
7 def test_manager(self): |
|
8 p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) |
|
9 p2 = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) |
|
10 |
|
11 self.assertQuerysetEqual( |
|
12 Person.objects.get_fun_people(), [ |
|
13 "Bugs Bunny" |
|
14 ], |
|
15 unicode |
|
16 ) |
|
17 # The RelatedManager used on the 'books' descriptor extends the default |
|
18 # manager |
|
19 self.assertTrue(isinstance(p2.books, PublishedBookManager)) |
|
20 |
|
21 b1 = Book.published_objects.create( |
|
22 title="How to program", author="Rodney Dangerfield", is_published=True |
|
23 ) |
|
24 b2 = Book.published_objects.create( |
|
25 title="How to be smart", author="Albert Einstein", is_published=False |
|
26 ) |
|
27 |
|
28 # The default manager, "objects", doesn't exist, because a custom one |
|
29 # was provided. |
|
30 self.assertRaises(AttributeError, lambda: Book.objects) |
|
31 |
|
32 # The RelatedManager used on the 'authors' descriptor extends the |
|
33 # default manager |
|
34 self.assertTrue(isinstance(b2.authors, PersonManager)) |
|
35 |
|
36 self.assertQuerysetEqual( |
|
37 Book.published_objects.all(), [ |
|
38 "How to program", |
|
39 ], |
|
40 lambda b: b.title |
|
41 ) |
|
42 |
|
43 c1 = Car.cars.create(name="Corvette", mileage=21, top_speed=180) |
|
44 c2 = Car.cars.create(name="Neon", mileage=31, top_speed=100) |
|
45 |
|
46 self.assertQuerysetEqual( |
|
47 Car.cars.order_by("name"), [ |
|
48 "Corvette", |
|
49 "Neon", |
|
50 ], |
|
51 lambda c: c.name |
|
52 ) |
|
53 |
|
54 self.assertQuerysetEqual( |
|
55 Car.fast_cars.all(), [ |
|
56 "Corvette", |
|
57 ], |
|
58 lambda c: c.name |
|
59 ) |
|
60 |
|
61 # Each model class gets a "_default_manager" attribute, which is a |
|
62 # reference to the first manager defined in the class. In this case, |
|
63 # it's "cars". |
|
64 |
|
65 self.assertQuerysetEqual( |
|
66 Car._default_manager.order_by("name"), [ |
|
67 "Corvette", |
|
68 "Neon", |
|
69 ], |
|
70 lambda c: c.name |
|
71 ) |