2006-05-02 01:31:56 +00:00
|
|
|
"""
|
2014-09-24 05:13:13 +00:00
|
|
|
Giving models custom methods
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
Any method you add to a model will be available to instances.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import datetime
|
|
|
|
|
2011-10-13 18:04:12 +00:00
|
|
|
from django.db import models
|
2012-08-12 10:32:08 +00:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2011-10-13 18:04:12 +00:00
|
|
|
|
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
class Article(models.Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
headline = models.CharField(max_length=100)
|
2006-05-02 01:31:56 +00:00
|
|
|
pub_date = models.DateField()
|
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return self.headline
|
|
|
|
|
|
|
|
def was_published_today(self):
|
|
|
|
return self.pub_date == datetime.date.today()
|
|
|
|
|
2006-06-04 00:23:51 +00:00
|
|
|
def articles_from_same_day_1(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
|
|
|
|
|
2006-06-04 00:23:51 +00:00
|
|
|
def articles_from_same_day_2(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
Verbose version of get_articles_from_same_day_1, which does a custom
|
|
|
|
database query for the sake of demonstration.
|
|
|
|
"""
|
|
|
|
from django.db import connection
|
2014-01-09 15:05:15 +00:00
|
|
|
with connection.cursor() as cursor:
|
|
|
|
cursor.execute("""
|
|
|
|
SELECT id, headline, pub_date
|
|
|
|
FROM custom_methods_article
|
|
|
|
WHERE pub_date = %s
|
|
|
|
AND id != %s""", [connection.ops.value_to_db_date(self.pub_date),
|
|
|
|
self.id])
|
|
|
|
return [self.__class__(*row) for row in cursor.fetchall()]
|