https://docs.djangoproject.com/zh-hans/2.1/topics/db/examples/many_to_many/

系统讲一下多对多关系:

第一个例子是官网的不需要定义附加表的多对多关系,其实也需要关系表,只不过关系表很简单,只有两列,即源对象id(from_*_id)和目标对象id(to_*_id),由系统自动添加:

操作的例子,官网介绍似乎很长,但仔细阅读发现内容不多,都是代码例子。总结起来一共几点:

1、为对象添加多对多关系前,需要保持对象,即写入数据库,产生id列,然后才能利用id列建立多对多关系表。

2、通过add()函数添加多对多关系,如a1.publications.add(p1),其中publications定义是:

publications = models.ManyToManyField(Publication)

3、多次添加同一个关系不会重复。add()的参数的类型不能错。

4、可以用create()函数,连建立to_*_id代表的目标对象,带add()新建对象到多对多关系表一起,一步完成两个操作。

5、可以从源对象查找到目标对象,也可以反向查找。

6、可用filter查找,并支持反向查找

7、.distinct().count()组合使用(不懂原文说的as well是指哪里也这样)

8、可以用exclude查找

9、delete删除一侧对象,则关系也随之删除。

10、从目标侧建立多对多关系。

11、remove()只删除关系,保留源侧和目标侧对象。

12、set()函数批量设关系

13、clear()函数清除所有关系

等等,详见原文。

Many-to-many relationships¶

To define a many-to-many relationship, use ManyToManyField.

In this example, an Article can be published in multiple Publication objects, and a Publication has multiple Article objects:

from django.db import modelsclass Publication(models.Model):title = models.CharField(max_length=30)def __str__(self):return self.titleclass Meta:ordering = ('title',)class Article(models.Model):headline = models.CharField(max_length=100)publications = models.ManyToManyField(Publication)def __str__(self):return self.headlineclass Meta:ordering = ('headline',)

What follows are examples of operations that can be performed using the Python API facilities. Note that if you are using an intermediate model for a many-to-many relationship, some of the related manager's methods are disabled, so some of these examples won't work with such models.

Create a few Publications:

>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
>>> p2 = Publication(title='Science News')
>>> p2.save()
>>> p3 = Publication(title='Science Weekly')
>>> p3.save()

Create an Article:

>>> a1 = Article(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 the Publications:

>>> a2 = Article(headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2)
>>> a2.publications.add(p3)

Adding a second time is OK, it will not duplicate the relation:

>>> a2.publications.add(p3)

Adding an object of the wrong type raises TypeError:

>>> a2.publications.add(a1)
Traceback (most recent call last):
...
TypeError: 'Publication' instance expected

Create and add a Publication to an Article in one step using create():

>>> new_publication = a2.publications.create(title='Highlights for Children')

Article objects have access to their related Publication objects:

>>> a1.publications.all()
<QuerySet [<Publication: The Python Journal>]>
>>> a2.publications.all()
<QuerySet [<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()
<QuerySet [<Article: NASA uses Python>]>
>>> p1.article_set.all()
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
>>> Publication.objects.get(id=4).article_set.all()
<QuerySet [<Article: NASA uses Python>]>

Many-to-many relationships can be queried using lookups across relationships:

>>> Article.objects.filter(publications__id=1)
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
>>> Article.objects.filter(publications__pk=1)
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
>>> Article.objects.filter(publications=1)
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
>>> Article.objects.filter(publications=p1)
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>>>> Article.objects.filter(publications__title__startswith="Science")
<QuerySet [<Article: NASA uses Python>, <Article: NASA uses Python>]>>>> Article.objects.filter(publications__title__startswith="Science").distinct()
<QuerySet [<Article: NASA uses Python>]>

The count() function respects distinct() as well:

>>> Article.objects.filter(publications__title__startswith="Science").count()
2>>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
1>>> Article.objects.filter(publications__in=[1,2]).distinct()
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
>>> Article.objects.filter(publications__in=[p1,p2]).distinct()
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>

Reverse m2m queries are supported (i.e., starting at the table that doesn't have a ManyToManyField):

>>> Publication.objects.filter(id=1)
<QuerySet [<Publication: The Python Journal>]>
>>> Publication.objects.filter(pk=1)
<QuerySet [<Publication: The Python Journal>]>>>> Publication.objects.filter(article__headline__startswith="NASA")
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>>>> Publication.objects.filter(article__id=1)
<QuerySet [<Publication: The Python Journal>]>
>>> Publication.objects.filter(article__pk=1)
<QuerySet [<Publication: The Python Journal>]>
>>> Publication.objects.filter(article=1)
<QuerySet [<Publication: The Python Journal>]>
>>> Publication.objects.filter(article=a1)
<QuerySet [<Publication: The Python Journal>]>>>> Publication.objects.filter(article__in=[1,2]).distinct()
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
>>> Publication.objects.filter(article__in=[a1,a2]).distinct()
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>

Excluding a related item works as you would expect, too (although the SQL involved is a little complex):

>>> Article.objects.exclude(publications=p2)
<QuerySet [<Article: Django lets you build Web apps easily>]>

If we delete a Publication, its Articles won't be able to access it:

>>> p1.delete()
>>> Publication.objects.all()
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]>
>>> a1 = Article.objects.get(pk=1)
>>> a1.publications.all()
<QuerySet []>

If we delete an Article, its Publications won't be able to access it:

>>> a2.delete()
>>> Article.objects.all()
<QuerySet [<Article: Django lets you build Web apps easily>]>
>>> p2.article_set.all()
<QuerySet []>

Adding via the 'other' end of an m2m:

>>> a4 = Article(headline='NASA finds intelligent life on Earth')
>>> a4.save()
>>> p2.article_set.add(a4)
>>> p2.article_set.all()
<QuerySet [<Article: NASA finds intelligent life on Earth>]>
>>> a4.publications.all()
<QuerySet [<Publication: Science News>]>

Adding via the other end using keywords:

>>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
>>> p2.article_set.all()
<QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
>>> a5 = p2.article_set.all()[1]
>>> a5.publications.all()
<QuerySet [<Publication: Science News>]>

Removing Publication from an Article:

>>> a4.publications.remove(p2)
>>> p2.article_set.all()
<QuerySet [<Article: Oxygen-free diet works wonders>]>
>>> a4.publications.all()
<QuerySet []>

And from the other end:

>>> p2.article_set.remove(a5)
>>> p2.article_set.all()
<QuerySet []>
>>> a5.publications.all()
<QuerySet []>

Relation sets can be set:

>>> a4.publications.all()
<QuerySet [<Publication: Science News>]>
>>> a4.publications.set([p3])
>>> a4.publications.all()
<QuerySet [<Publication: Science Weekly>]>

Relation sets can be cleared:

>>> p2.article_set.clear()
>>> p2.article_set.all()
<QuerySet []>

And you can clear from the other end:

>>> p2.article_set.add(a4, a5)
>>> p2.article_set.all()
<QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
>>> a4.publications.all()
<QuerySet [<Publication: Science News>, <Publication: Science Weekly>]>
>>> a4.publications.clear()
>>> a4.publications.all()
<QuerySet []>
>>> p2.article_set.all()
<QuerySet [<Article: Oxygen-free diet works wonders>]>

Recreate the Article and Publication we have deleted:

>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
>>> a2 = Article(headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2, p3)

Bulk delete some Publications - references to deleted publications should go:

>>> Publication.objects.filter(title__startswith='Science').delete()
>>> Publication.objects.all()
<QuerySet [<Publication: Highlights for Children>, <Publication: The Python Journal>]>
>>> Article.objects.all()
<QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>, <Article: Oxygen-free diet works wonders>]>
>>> a2.publications.all()
<QuerySet [<Publication: The Python Journal>]>

Bulk delete some articles - references to deleted objects should go:

>>> q = Article.objects.filter(headline__startswith='Django')
>>> print(q)
<QuerySet [<Article: Django lets you build Web apps easily>]>
>>> q.delete()

After the delete(), the QuerySet cache needs to be cleared, and the referenced objects should be gone:

>>> print(q)
<QuerySet []>
>>> p1.article_set.all()
<QuerySet [<Article: NASA uses Python>]>

除了简单的多对多关系,还有可自定义字段的多对多关系表:

其实相当于自定义一个class,有两个外键,分别是源对象和目标对象,其余字段可以自定义,如:

class Membership(models.Model):

person = models.ForeignKey(Person, on_delete=models.CASCADE)

group = models.ForeignKey(Group, on_delete=models.CASCADE)

date_joined = models.DateField()

invite_reason = models.CharField(max_length=64)

注意的是这种自定义的关系表不能用add(), create(), or set()来创建关系,因为自定义的多对多关系还有其他字段需要补充。

这种多对多关系的建立和其他对象建立一样,用普通方式:

Membership.objects.create()

Extra fields on many-to-many relationships¶

When you’re only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.

For example, consider the case of an application tracking the musical groups which musicians belong to. There is a many-to-many relationship between a person and the groups of which they are a member, so you could use a ManyToManyField to represent this relationship. However, there is a lot of detail about the membership that you might want to collect, such as the date at which the person joined the group.

For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this:

from django.db import modelsclass Person(models.Model):name = models.CharField(max_length=128)def __str__(self):return self.nameclass Group(models.Model):name = models.CharField(max_length=128)members = models.ManyToManyField(Person, through='Membership')def __str__(self):return self.nameclass Membership(models.Model):person = models.ForeignKey(Person, on_delete=models.CASCADE)group = models.ForeignKey(Group, on_delete=models.CASCADE)date_joined = models.DateField()invite_reason = models.CharField(max_length=64)

When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the many-to-many relationship. This explicit declaration defines how the two models are related.

There are a few restrictions on the intermediate model:

  • Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.through_fields. If you have more than one foreign key and through_fields is not specified, a validation error will be raised. A similar restriction applies to the foreign key to the target model (this would be Person in our example).
  • For a model which has a many-to-many relationship to itself through an intermediary model, two foreign keys to the same model are permitted, but they will be treated as the two (different) sides of the many-to-many relationship. If there are more than two foreign keys though, you must also specify through_fields as above, or a validation error will be raised.
  • When defining a many-to-many relationship from a model to itself, using an intermediary model, you must use symmetrical=False (see the model field reference).

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:

>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
...     date_joined=date(1962, 8, 16),
...     invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>
>>> ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>
>>> m2 = Membership.objects.create(person=paul, group=beatles,
...     date_joined=date(1960, 8, 1),
...     invite_reason="Wanted to form a band.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>

ZJadjacent.objects.get_or_create(cellfrom=_source, cellto=_target)

遇到效率问题,邻区表80万条,通过小区实例作为参数需要先查找小区对象,会耗费宝贵的处理时间,可不可以用小区的主键值作为参数呢,可以的!但参数名必须增加_id。如下面的例子,_source、_target是id值,参数名为cellfrom_id、cellto_id:

ZJadjacent.objects.get_or_create(cellfrom_id=_source, cellto_id=_target)

我会另外写一篇文档详细说明。

Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships:

>>> # The following statements will not work
>>> beatles.members.add(john)
>>> beatles.members.create(name="George Harrison")
>>> beatles.members.set([john, paul, ringo, george])

Why? You can’t just create a relationship between a Person and a Group - you need to specify all the detail for the relationship required by the Membership model. The simple add, create and assignment calls don’t provide a way to specify this extra detail. As a result, they are disabled for many-to-many relationships that use an intermediate model. The only way to create this type of relationship is to create instances of the intermediate model.

The remove() method is disabled for similar reasons. For example, if the custom through table defined by the intermediate model does not enforce uniqueness on the (model1, model2) pair, a remove() call would not provide enough information as to which intermediate model instance should be deleted:

>>> Membership.objects.create(person=ringo, group=beatles,
...     date_joined=date(1968, 9, 4),
...     invite_reason="You've been gone for a month and we miss you.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
>>> # This will not work because it cannot tell which membership to remove
>>> beatles.members.remove(ringo)

However, the clear() method can be used to remove all many-to-many relationships for an instance:

>>> # Beatles have broken up
>>> beatles.members.clear()
>>> # Note that this deletes the intermediate model instances
>>> Membership.objects.all()
<QuerySet []>

Once you have established the many-to-many relationships by creating instances of your intermediate model, you can issue queries. Just as with normal many-to-many relationships, you can query using the attributes of the many-to-many-related model:

# Find all the groups with a member whose name starts with 'Paul'
>>> Group.objects.filter(members__name__startswith='Paul')
<QuerySet [<Group: The Beatles>]>

As you are using an intermediate model, you can also query on its attributes:

# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
...     group__name='The Beatles',
...     membership__date_joined__gt=date(1961,1,1))
<QuerySet [<Person: Ringo Starr]>

If you need to access a membership’s information you may do so by directly querying the Membership model:

>>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'

Another way to access the same information is by querying the many-to-many reverse relationship from a Person object:

>>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'

补充,自定义多对多关系表:

https://docs.djangoproject.com/zh-hans/2.1/ref/models/fields/#django.db.models.ManyToManyField.through_fields

ManyToManyField.through_fields

Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, consider the following models:

from django.db import modelsclass Person(models.Model):name = models.CharField(max_length=50)class Group(models.Model):name = models.CharField(max_length=128)members = models.ManyToManyField(Person,through='Membership',through_fields=('group', 'person'),)class Membership(models.Model):group = models.ForeignKey(Group, on_delete=models.CASCADE)person = models.ForeignKey(Person, on_delete=models.CASCADE)inviter = models.ForeignKey(Person,on_delete=models.CASCADE,related_name="membership_invites",)invite_reason = models.CharField(max_length=64)

Membership has two foreign keys to Person (person and inviter), which makes the relationship ambiguous and Django can't know which one to use. In this case, you must explicitly specify which foreign keys Django should use using through_fields, as in the example above.

through_fields accepts a 2-tuple ('field1', 'field2'), where field1 is the name of the foreign key to the model the ManyToManyField is defined on (group in this case), and field2 the name of the foreign key to the target model (person in this case).

When you have more than one foreign key on an intermediary model to any (or even both) of the models participating in a many-to-many relationship, you must specify through_fields. This also applies to recursive relationships when an intermediary model is used and there are more than two foreign keys to the model, or you want to explicitly specify which two Django should use.

Recursive relationships using an intermediary model are always defined as non-symmetrical -- that is, with symmetrical=False -- therefore, there is the concept of a "source" and a "target". In that case 'field1' will be treated as the "source" of the relationship and 'field2' as the "target".

ManyToManyField多对多关系(django Many-to-many relationships)相关推荐

  1. Django 之多对多关系

    1. 多对多关系 作者 <--> 书籍 1. 表结构设计 1. SQL版 -- 创建作者表 create table author( id int primary key auto_inc ...

  2. Django的ManyToManyField(多对多)的使用以及through的作用

    创建一个经典的多对多关系:一本书可以有多个作者,一个作者可以有多本书(如下) 进行数据迁移,然后我们使用python manage.py sqlmigrate app(应用名) 迁移文件名 查看一下s ...

  3. Dango-之多对多关系—基于双下划线的查询

    一对一的反向查询用表名不加_set,一对多的反向查询表名加_set 前面写了一对多的关系,在这里升级下写下多对多的关系~~ 我们从前面的小项目app01中创建了一对多关系的Publish表,从这里我们 ...

  4. python使用ORM之如何调用多对多关系

    目录 在models.py中,我创建了两张表,他们分别是作者表和书籍表,且之间的关系是多对多. ---------------------------------------------------- ...

  5. NHibernate之旅(11):探索多对多关系及其关联查询

    本节内容 多对多关系引入 多对多映射关系 多对多关联查询 1.原生SQL关联查询 2.HQL关联查询 3.Criteria API关联查询 结语 多对多关系引入 让我们再次回顾在第二篇中建立的数据模型 ...

  6. flask_sqlalchemy 多对多 关系 对中间表的操作

    文章目录 注意 多对多关系表 创建(同时添加中间表page_tag) 不可以只查询一张表来删除(这种做法只能删除一部分.) 应该查询2张表后删除(只删除 中间表page_tag 中的数据) 添加(只添 ...

  7. 【MySql】8.多对多关系表

    多对多关系: 比如在常见的订单管理数据库当中"产品"表和"订单"表之间的关系.单个订单中可以包含多个产品.另一方面,一个产品可能出现在多个订单中.因此,对于&q ...

  8. mysql表中的多对多关系表_「一对多」关系型数据库中一对多,多对一,多对多关系(详细) - seo实验室...

    一对多 在关系型数据库中,通过外键将表跟表之间联系在了一起. 一个班级有很多学生,外键维护在学生的一方,也就是多的一方.(在做页面设计的时候,需要把两个表连接到一块查询信息) 建立一个student和 ...

  9. SQLAlchemy_定义(一对一/一对多/多对多)关系

    SQLAlchemy_定义(一对一/一对多/多对多)关系 目录 Basic Relationship Patterns One To Many One To One Many To Many Basi ...

最新文章

  1. 大数据可视化技术面临的挑战及应对措施
  2. 那些年陪我走过一个又一个加班夜晚的程序员鼓励师们
  3. OJ1043: 最大值(C语言)
  4. ARM平台交叉编译valgrind
  5. Go在容器运行时要注意的细节
  6. 代码生成工具系列-----代码生成工具(CodeEasy)介绍
  7. 获取系统分辨率_100 GHz传送带高速成像系统
  8. 对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
  9. 基于multisim的电子秒表
  10. 阿里云服务器地域的选择
  11. QCC512x QCC302x 打开 BLE 功能
  12. 自我介绍一分钟范文(碎的)
  13. faster-rcnn 训练自己的数据集
  14. 注意2022年软考网络规划设计师考试新版大纲和教程已出炉
  15. 朝阳医院2018年销售数据分析
  16. TheDAO被攻击事件考察报告
  17. 【SAP】为什么2023年后ABAP仍有广阔前景「来听听ChatGPT怎么说」
  18. Total Access Emailer维护审计跟踪
  19. 弘辽科技:拼多多又搞事,这些商家又受影响。
  20. 简单的利用FramWork 生成iqd文件的过程

热门文章

  1. Linux下制作Windows启动U盘的工具
  2. Vue笔记_03_使用Vue脚手架
  3. 问世 20 年,QQ 要推出注销功能
  4. WiFi - AP 隔离
  5. Element Plus里的el-table表格
  6. 开发技术前线 第十一期
  7. 用css画三角形、爱心、钻石
  8. 某网校之Cocos2d-x视频教程
  9. 开启微信悬浮窗权限有什么用_魅族这个值得吹爆的功能,你也能用上了
  10. 基于python+vue+elementUI+django高校教室管理系统(前后端分离)#毕业设计