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
10
from django.utils.encoding import python_2_unicode_compatible
13
@python_2_unicode_compatible
14
class Article(models.Model):
15
headline = models.CharField(max_length=100)
16
pub_date = models.DateField()
21
def was_published_today(self):
22
return self.pub_date == datetime.date.today()
24
def articles_from_same_day_1(self):
25
return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
27
def articles_from_same_day_2(self):
29
Verbose version of get_articles_from_same_day_1, which does a custom
30
database query for the sake of demonstration.
32
from django.db import connection
33
cursor = connection.cursor()
35
SELECT id, headline, pub_date
36
FROM custom_methods_article
38
AND id != %s""", [connection.ops.value_to_db_date(self.pub_date),
40
return [self.__class__(*row) for row in cursor.fetchall()]