(self)
| 19 | Article._meta.get_latest_by = self._article_get_latest_by |
| 20 | |
| 21 | def test_earliest(self): |
| 22 | # Because no Articles exist yet, earliest() raises ArticleDoesNotExist. |
| 23 | with self.assertRaises(Article.DoesNotExist): |
| 24 | Article.objects.earliest() |
| 25 | |
| 26 | a1 = Article.objects.create( |
| 27 | headline="Article 1", |
| 28 | pub_date=datetime(2005, 7, 26), |
| 29 | expire_date=datetime(2005, 9, 1), |
| 30 | ) |
| 31 | a2 = Article.objects.create( |
| 32 | headline="Article 2", |
| 33 | pub_date=datetime(2005, 7, 27), |
| 34 | expire_date=datetime(2005, 7, 28), |
| 35 | ) |
| 36 | a3 = Article.objects.create( |
| 37 | headline="Article 3", |
| 38 | pub_date=datetime(2005, 7, 28), |
| 39 | expire_date=datetime(2005, 8, 27), |
| 40 | ) |
| 41 | a4 = Article.objects.create( |
| 42 | headline="Article 4", |
| 43 | pub_date=datetime(2005, 7, 28), |
| 44 | expire_date=datetime(2005, 7, 30), |
| 45 | ) |
| 46 | |
| 47 | # Get the earliest Article. |
| 48 | self.assertEqual(Article.objects.earliest(), a1) |
| 49 | # Get the earliest Article that matches certain filters. |
| 50 | self.assertEqual( |
| 51 | Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest(), a2 |
| 52 | ) |
| 53 | |
| 54 | # Pass a custom field name to earliest() to change the field that's |
| 55 | # used to determine the earliest object. |
| 56 | self.assertEqual(Article.objects.earliest("expire_date"), a2) |
| 57 | self.assertEqual( |
| 58 | Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).earliest( |
| 59 | "expire_date" |
| 60 | ), |
| 61 | a2, |
| 62 | ) |
| 63 | |
| 64 | # earliest() overrides any other ordering specified on the query. |
| 65 | # Refs #11283. |
| 66 | self.assertEqual(Article.objects.order_by("id").earliest(), a1) |
| 67 | |
| 68 | # Error is raised if the user forgot to add a get_latest_by |
| 69 | # in the Model.Meta |
| 70 | Article.objects.model._meta.get_latest_by = None |
| 71 | with self.assertRaisesMessage( |
| 72 | ValueError, |
| 73 | "earliest() and latest() require either fields as positional " |
| 74 | "arguments or 'get_latest_by' in the model's Meta.", |
| 75 | ): |
| 76 | Article.objects.earliest() |
| 77 | |
| 78 | # Earliest publication date, earliest expire date. |
nothing calls this directly
no test coverage detected