/tests/modeltests/custom_methods/models.py
Python | 36 lines | 21 code | 6 blank | 9 comment | 0 complexity | 9d4444decb627578caf2653c9d83a5f1 MD5 | raw file
Possible License(s): BSD-3-Clause
1""" 23. Giving models custom methods 3 4Any method you add to a model will be available to instances. 5""" 6 7from django.db import models 8import datetime 9 10class Article(models.Model): 11 headline = models.CharField(max_length=100) 12 pub_date = models.DateField() 13 14 def __unicode__(self): 15 return self.headline 16 17 def was_published_today(self): 18 return self.pub_date == datetime.date.today() 19 20 def articles_from_same_day_1(self): 21 return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id) 22 23 def articles_from_same_day_2(self): 24 """ 25 Verbose version of get_articles_from_same_day_1, which does a custom 26 database query for the sake of demonstration. 27 """ 28 from django.db import connection 29 cursor = connection.cursor() 30 cursor.execute(""" 31 SELECT id, headline, pub_date 32 FROM custom_methods_article 33 WHERE pub_date = %s 34 AND id != %s""", [connection.ops.value_to_db_date(self.pub_date), 35 self.id]) 36 return [self.__class__(*row) for row in cursor.fetchall()]