2 3. Giving models custom methods
4 Any method you add to a model will be available to instances.
9 from django
.db
import models
12 class Article(models
.Model
):
13 headline
= models
.CharField(max_length
=100)
14 pub_date
= models
.DateField()
16 def __unicode__(self
):
19 def was_published_today(self
):
20 return self
.pub_date
== datetime
.date
.today()
22 def articles_from_same_day_1(self
):
23 return Article
.objects
.filter(pub_date
=self
.pub_date
).exclude(id=self
.id)
25 def articles_from_same_day_2(self
):
27 Verbose version of get_articles_from_same_day_1, which does a custom
28 database query for the sake of demonstration.
30 from django
.db
import connection
31 cursor
= connection
.cursor()
33 SELECT id, headline, pub_date
34 FROM custom_methods_article
36 AND id != %s""", [connection
.ops
.value_to_db_date(self
.pub_date
),
38 return [self
.__class
__(*row
) for row
in cursor
.fetchall()]