~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to tests/custom_methods/models.py

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

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