From ade65b2355d33e6711392a35775eb706a54f83b8 Mon Sep 17 00:00:00 2001 From: Anna Astori Date: Sat, 20 Jul 2024 09:32:05 -0400 Subject: [PATCH] Add created_at timestamp --- taggit/managers.py | 6 ++++++ taggit/models.py | 3 +++ tests/tests.py | 10 ++++++++++ 3 files changed, 19 insertions(+) diff --git a/taggit/managers.py b/taggit/managers.py index 0ff8e976..8841d946 100644 --- a/taggit/managers.py +++ b/taggit/managers.py @@ -400,6 +400,12 @@ def clear(self): using=db, ) + def most_recent(self): + return self.latest("created_at") + + def least_recent(self): + return self.earliest("created_at") + def most_common(self, min_count=None, extra_filters=None): queryset = ( self.get_queryset(extra_filters) diff --git a/taggit/models.py b/taggit/models.py index 8d7f60bd..d29c0e71 100644 --- a/taggit/models.py +++ b/taggit/models.py @@ -6,6 +6,8 @@ from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy +from django.utils import timezone + try: from unidecode import unidecode @@ -183,6 +185,7 @@ class Meta: class TaggedItem(GenericTaggedItemBase, TaggedItemBase): + created_at = models.DateTimeField(default=timezone.now, blank=True, null=True) class Meta: verbose_name = _("tagged item") verbose_name_plural = _("tagged items") diff --git a/tests/tests.py b/tests/tests.py index 79489598..05903448 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -902,6 +902,16 @@ def test_extra_fields(self): self.assertEqual(apple, self.food_model.objects.get(tags__official=False)) + def test_timestamps(self): + apple = self.food_model.objects.create(name="apple") + apple.tags.add("red") + apple.tags.add("delicious") + most_recent = apple.tags.most_recent() + least_recent = apple.tags.least_recent() + + self.assertEqual(most_recent.name, "delicious") + self.assertEqual(least_recent.name, "red") + def test_get_tags_with_count(self): apple = self.food_model.objects.create(name="apple") apple.tags.add("red", "green", "delicious")