~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant, Eddy Mulyono
  • Date: 2008-09-16 12:18:47 UTC
  • mfrom: (1.1.5 upstream) (4.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080916121847-mg225rg5mnsdqzr0
Tags: 1.0-1ubuntu1
* Merge from Debian (LP: #264191), remaining changes:
  - Run test suite on build.

[Eddy Mulyono]
* Update patch to workaround network test case failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
"""
2
2
5. Many-to-many relationships
3
3
 
4
 
To define a many-to-many relationship, use ManyToManyField().
 
4
To define a many-to-many relationship, use ``ManyToManyField()``.
5
5
 
6
 
In this example, an article can be published in multiple publications,
7
 
and a publication has multiple articles.
 
6
In this example, an ``Article`` can be published in multiple ``Publication``
 
7
objects, and a ``Publication`` has multiple ``Article`` objects.
8
8
"""
9
9
 
10
10
from django.db import models
11
11
 
12
12
class Publication(models.Model):
13
 
    title = models.CharField(maxlength=30)
 
13
    title = models.CharField(max_length=30)
14
14
 
15
 
    def __str__(self):
 
15
    def __unicode__(self):
16
16
        return self.title
17
17
 
18
18
    class Meta:
19
19
        ordering = ('title',)
20
20
 
21
21
class Article(models.Model):
22
 
    headline = models.CharField(maxlength=100)
 
22
    headline = models.CharField(max_length=100)
23
23
    publications = models.ManyToManyField(Publication)
24
24
 
25
 
    def __str__(self):
 
25
    def __unicode__(self):
26
26
        return self.headline
27
27
 
28
28
    class Meta:
39
39
 
40
40
# Create an Article.
41
41
>>> a1 = Article(id=None, headline='Django lets you build Web apps easily')
 
42
 
 
43
# You can't associate it with a Publication until it's been saved.
 
44
>>> a1.publications.add(p1)
 
45
Traceback (most recent call last):
 
46
...
 
47
ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
 
48
 
 
49
# Save it!
42
50
>>> a1.save()
43
51
 
44
52
# Associate the Article with a Publication.
126
134
>>> Publication.objects.filter(article__in=[a1,a2]).distinct()
127
135
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
128
136
 
 
137
# Excluding a related item works as you would expect, too (although the SQL
 
138
# involved is a little complex).
 
139
>>> Article.objects.exclude(publications=p2)
 
140
[<Article: Django lets you build Web apps easily>]
 
141
 
129
142
# If we delete a Publication, its Articles won't be able to access it.
130
143
>>> p1.delete()
131
144
>>> Publication.objects.all()