Skip to content

Instantly share code, notes, and snippets.

@linxuedong
Last active June 30, 2023 22:35
Show Gist options
  • Save linxuedong/72677d04a6ca7f895b9166f7445eb82a to your computer and use it in GitHub Desktop.
Save linxuedong/72677d04a6ca7f895b9166f7445eb82a to your computer and use it in GitHub Desktop.
Django test auto_now DateTime Fields
class Article(models.Model):    
    title = models.CharField()
    content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

I want to an article which was created and modified yesterday. And test the things today.

from datetime import timedelta, datetime
import mock
class YesterdayTestCase(TestCase):
    def setUp(self):
        yesterday = datetime.now() - timedelta(days=1)
        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = yesterday
            self.article = Article.objects.create(
                title = 'Article Title',
                content = 'Article Content'
            )

            
@linxuedong
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment