Posted By

magicrebirth on 01/27/10


Tagged

model django m2mthrough


Versions (?)

Django: instantiating M2M-through models


 / Published in: Python
 

URL: http://docs.djangoproject.com/en/1.1/topics/db/models/#extra-fields-on-many-to-many-relationships

Now that you have set up your ManyToManyField to use your intermediary model (Membership, in this case), you're ready to start creating some many-to-many relationships. You do this by creating instances of the intermediate model:

  1. >>> ringo = Person.objects.create(name="Ringo Starr")
  2. >>> paul = Person.objects.create(name="Paul McCartney")
  3. >>> beatles = Group.objects.create(name="The Beatles")
  4. >>> m1 = Membership(person=ringo, group=beatles,
  5. ... date_joined=date(1962, 8, 16),
  6. ... invite_reason= "Needed a new drummer.")
  7. >>> m1.save()
  8. >>> beatles.members.all()
  9. [<Person: Ringo Starr>]
  10. >>> ringo.group_set.all()
  11. [<Group: The Beatles>]
  12. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  13. ... date_joined=date(1960, 8, 1),
  14. ... invite_reason= "Wanted to form a band.")
  15. >>> beatles.members.all()
  16. [<Person: Ringo Starr>, <Person: Paul McCartney>]
  17.  
  18. # Unlike normal many-to-many fields, you can't use add, create, or assignment (i.e., Beatles.members = [...]) to create relationships:
  19.  
  20.  
  21. # THIS WILL NOT WORK
  22. >>> beatles.members.add(john)
  23. # NEITHER WILL THIS
  24. >>> beatles.members.create(name="George Harrison")
  25. # AND NEITHER WILL THIS
  26. >>> beatles.members = [john, paul, ringo, george]
  27.  
  28. # Beatles have broken up
  29. >>> beatles.members.clear()

Report this snippet  

You need to login to post a comment.