/tests/modeltests/custom_methods/models.py

https://code.google.com/p/mango-py/ · Python · 36 lines · 21 code · 6 blank · 9 comment · 1 complexity · 9d4444decb627578caf2653c9d83a5f1 MD5 · raw file

  1. """
  2. 3. Giving models custom methods
  3. Any method you add to a model will be available to instances.
  4. """
  5. from django.db import models
  6. import datetime
  7. class Article(models.Model):
  8. headline = models.CharField(max_length=100)
  9. pub_date = models.DateField()
  10. def __unicode__(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. cursor = connection.cursor()
  23. cursor.execute("""
  24. SELECT id, headline, pub_date
  25. FROM custom_methods_article
  26. WHERE pub_date = %s
  27. AND id != %s""", [connection.ops.value_to_db_date(self.pub_date),
  28. self.id])
  29. return [self.__class__(*row) for row in cursor.fetchall()]