Return to Snippet

Revision: 22995
at January 27, 2010 07:25 by magicrebirth


Initial Code
>>> from mysite.models import Publication, Article

# Create a couple of Publications.
>>> p1 = Publication(id=None, title='The Python Journal')
>>> p1.save()
>>> p2 = Publication(id=None, title='Science News')
>>> p2.save()
>>> p3 = Publication(id=None, title='Science Weekly')
>>> p3.save()

# Create an Article.
>>> a1 = Article(id=None, headline='Django lets you build Web apps easily')

# You can't associate it with a Publication until it's been saved.
>>> a1.publications.add(p1)
Traceback (most recent call last):
...
ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.

# Save it!
>>> a1.save()

# Associate the Article with a Publication.
>>> a1.publications.add(p1)

# Create another Article, and set it to appear in both Publications.
>>> a2 = Article(id=None, headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2)
>>> a2.publications.add(p3)

# Adding a second time is OK
>>> a2.publications.add(p3)

# Add a Publication directly via publications.add by using keyword arguments.
>>> new_publication = a2.publications.create(title='Highlights for Children')

# Article objects have access to their related Publication objects.
>>> a1.publications.all()
[<Publication: The Python Journal>]
>>> a2.publications.all()
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]

# Publication objects have access to their related Article objects.
>>> p2.article_set.all()
[<Article: NASA uses Python>]
>>> p1.article_set.all()
[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
>>> Publication.objects.get(id=4).article_set.all()
[<Article: NASA uses Python>]

Initial URL
http://www.djangoproject.com/documentation/models/many_to_many/

Initial Description

                                

Initial Title
Django: instantiating (simple) M2M models

Initial Tags
django

Initial Language
Django