| 1 |
""" |
| 2 |
Giving models custom methods |
| 3 |
|
| 4 |
Any method you add to a model will be available to instances. |
| 5 |
""" |
| 6 |
|
| 7 |
import datetime |
| 8 |
|
| 9 |
from django.db import models |
| 10 |
|
| 11 |
|
| 12 |
class Article(models.Model): |
| 13 |
headline = models.CharField(max_length=100) |
| 14 |
pub_date = models.DateField() |
| 15 |
|
| 16 |
def __str__(self): |
| 17 |
return self.headline |
| 18 |
|
| 19 |
def was_published_today(self): |
| 20 |
return self.pub_date == datetime.date.today() |
| 21 |
|
| 22 |
def articles_from_same_day_1(self): |
| 23 |
return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id) |
| 24 |
|
| 25 |
def articles_from_same_day_2(self): |
| 26 |
""" |
| 27 |
Verbose version of get_articles_from_same_day_1, which does a custom |
| 28 |
database query for the sake of demonstration. |
| 29 |
""" |
| 30 |
from django.db import connection |
| 31 |
|
| 32 |
with connection.cursor() as cursor: |
| 33 |
cursor.execute( |
| 34 |
""" |
| 35 |
SELECT id, headline, pub_date |
| 36 |
FROM custom_methods_article |
| 37 |
WHERE pub_date = %s |
| 38 |
AND id != %s""", |
| 39 |
[connection.ops.adapt_datefield_value(self.pub_date), self.id], |
| 40 |
) |
| 41 |
return [self.__class__(*row) for row in cursor.fetchall()] |