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