Django:通过模型实例化M2M

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django:通过模型实例化M2M相关的知识,希望对你有一定的参考价值。

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()

以上是关于Django:通过模型实例化M2M的主要内容,如果未能解决你的问题,请参考以下文章

更新 Django 中现有的 M2M 关系

django m2m 模型不同步

Django - 删除 M2M 字段但保留连接表

在 Django 中过滤第二级多对多关系

通过 m2m 关系的直通表的值过滤 django 查询集

创建片段而不从 java 代码实例化它