2
3. Giving models custom methods
4
Any method you add to a model will be available to instances.
7
from django.db import models
10
class Article(models.Model):
11
headline = models.CharField(max_length=100)
12
pub_date = models.DateField()
14
def __unicode__(self):
17
def was_published_today(self):
18
return self.pub_date == datetime.date.today()
20
def articles_from_same_day_1(self):
21
return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
23
def articles_from_same_day_2(self):
25
Verbose version of get_articles_from_same_day_1, which does a custom
26
database query for the sake of demonstration.
28
from django.db import connection
29
cursor = connection.cursor()
31
SELECT id, headline, pub_date
32
FROM custom_methods_article
34
AND id != %s""", [connection.ops.value_to_db_date(self.pub_date),
36
# The asterisk in "(*row)" tells Python to expand the list into
37
# positional arguments to Article().
38
return [self.__class__(*row) for row in cursor.fetchall()]
40
__test__ = {'API_TESTS':"""
41
# Create a couple of Articles.
42
>>> from datetime import date
43
>>> a = Article(id=None, headline='Area man programs in Python', pub_date=date(2005, 7, 27))
45
>>> b = Article(id=None, headline='Beatles reunite', pub_date=date(2005, 7, 27))
48
# Test the custom methods.
49
>>> a.was_published_today()
51
>>> a.articles_from_same_day_1()
52
[<Article: Beatles reunite>]
53
>>> a.articles_from_same_day_2()
54
[<Article: Beatles reunite>]
55
>>> b.articles_from_same_day_1()
56
[<Article: Area man programs in Python>]
57
>>> b.articles_from_same_day_2()
58
[<Article: Area man programs in Python>]