~kkubasik/django/aggregation-branch

« back to all changes in this revision

Viewing changes to tests/modeltests/custom_methods/models.py

  • Committer: adrian
  • Date: 2006-05-02 01:31:56 UTC
  • Revision ID: vcs-imports@canonical.com-20060502013156-2941fcd40d080649
MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards-incompatible. Please read http://code.djangoproject.com/wiki/RemovingTheMagic for upgrade instructions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
3. Giving models custom methods and custom managers
 
3
 
 
4
Any method you add to a model will be available to instances.
 
5
"""
 
6
 
 
7
from django.db import models
 
8
import datetime
 
9
 
 
10
class Article(models.Model):
 
11
    headline = models.CharField(maxlength=100)
 
12
    pub_date = models.DateField()
 
13
 
 
14
    def __repr__(self):
 
15
        return self.headline
 
16
 
 
17
    def was_published_today(self):
 
18
        return self.pub_date == datetime.date.today()
 
19
 
 
20
    def get_articles_from_same_day_1(self):
 
21
        return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
 
22
 
 
23
    def get_articles_from_same_day_2(self):
 
24
        """
 
25
        Verbose version of get_articles_from_same_day_1, which does a custom
 
26
        database query for the sake of demonstration.
 
27
        """
 
28
        from django.db import connection
 
29
        cursor = connection.cursor()
 
30
        cursor.execute("""
 
31
            SELECT id, headline, pub_date
 
32
            FROM custom_methods_article
 
33
            WHERE pub_date = %s
 
34
                AND id != %s""", [str(self.pub_date), self.id])
 
35
        # The asterisk in "(*row)" tells Python to expand the list into
 
36
        # positional arguments to Article().
 
37
        return [self.__class__(*row) for row in cursor.fetchall()]
 
38
 
 
39
API_TESTS = """
 
40
# Create a couple of Articles.
 
41
>>> from datetime import date
 
42
>>> a = Article(id=None, headline='Area man programs in Python', pub_date=date(2005, 7, 27))
 
43
>>> a.save()
 
44
>>> b = Article(id=None, headline='Beatles reunite', pub_date=date(2005, 7, 27))
 
45
>>> b.save()
 
46
 
 
47
# Test the custom methods.
 
48
>>> a.was_published_today()
 
49
False
 
50
>>> a.get_articles_from_same_day_1()
 
51
[Beatles reunite]
 
52
>>> a.get_articles_from_same_day_2()
 
53
[Beatles reunite]
 
54
>>> b.get_articles_from_same_day_1()
 
55
[Area man programs in Python]
 
56
>>> b.get_articles_from_same_day_2()
 
57
[Area man programs in Python]
 
58
"""