models.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """
  2. Giving models custom methods
  3. Any method you add to a model will be available to instances.
  4. """
  5. import datetime
  6. from django.db import models
  7. class Article(models.Model):
  8. headline = models.CharField(max_length=100)
  9. pub_date = models.DateField()
  10. def __str__(self):
  11. return self.headline
  12. def was_published_today(self):
  13. return self.pub_date == datetime.date.today()
  14. def articles_from_same_day_1(self):
  15. return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
  16. def articles_from_same_day_2(self):
  17. """
  18. Verbose version of get_articles_from_same_day_1, which does a custom
  19. database query for the sake of demonstration.
  20. """
  21. from django.db import connection
  22. with connection.cursor() as cursor:
  23. cursor.execute(
  24. """
  25. SELECT id, headline, pub_date
  26. FROM custom_methods_article
  27. WHERE pub_date = %s
  28. AND id != %s""",
  29. [connection.ops.adapt_datefield_value(self.pub_date), self.id],
  30. )
  31. return [self.__class__(*row) for row in cursor.fetchall()]