Posted By

magicrebirth on 01/27/10


Tagged

model django m2m


Versions (?)

Django: instantiating (simple) M2M models


 / Published in: Django
 

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

  1. >>> from mysite.models import Publication, Article
  2.  
  3. # Create a couple of Publications.
  4. >>> p1 = Publication(id=None, title='The Python Journal')
  5. >>> p1.save()
  6. >>> p2 = Publication(id=None, title='Science News')
  7. >>> p2.save()
  8. >>> p3 = Publication(id=None, title='Science Weekly')
  9. >>> p3.save()
  10.  
  11. # Create an Article.
  12. >>> a1 = Article(id=None, headline='Django lets you build Web apps easily')
  13.  
  14. # You can't associate it with a Publication until it's been saved.
  15. >>> a1.publications.add(p1)
  16. Traceback (most recent call last):
  17. ...
  18. ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
  19.  
  20. # Save it!
  21. >>> a1.save()
  22.  
  23. # Associate the Article with a Publication.
  24. >>> a1.publications.add(p1)
  25.  
  26. # Create another Article, and set it to appear in both Publications.
  27. >>> a2 = Article(id=None, headline='NASA uses Python')
  28. >>> a2.save()
  29. >>> a2.publications.add(p1, p2)
  30. >>> a2.publications.add(p3)
  31.  
  32. # Adding a second time is OK
  33. >>> a2.publications.add(p3)
  34.  
  35. # Add a Publication directly via publications.add by using keyword arguments.
  36. >>> new_publication = a2.publications.create(title='Highlights for Children')
  37.  
  38. # Article objects have access to their related Publication objects.
  39. >>> a1.publications.all()
  40. [<Publication: The Python Journal>]
  41. >>> a2.publications.all()
  42. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
  43.  
  44. # Publication objects have access to their related Article objects.
  45. >>> p2.article_set.all()
  46. [<Article: NASA uses Python>]
  47. >>> p1.article_set.all()
  48. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  49. >>> Publication.objects.get(id=4).article_set.all()
  50. [<Article: NASA uses Python>]

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: liange on June 21, 2011

Django projects and the ideas are quite different. This is something a new concept I have seen here. SEO Reseller

You need to login to post a comment.