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 models
class Publication(models.Model):
title = models.CharField(max_length=30)
def __str__(self):
return self.title
class Meta:
ordering = ('title',)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
def __str__(self):
return self.headline
class 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()
]>
>>> a2.publications.all()
, , , ]>
Publication
objects have access to their related Article
objects:
>>> p2.article_set.all()
]>
>>> p1.article_set.all()
, ]>
>>> Publication.objects.get(id=4).article_set.all()
]>
Many-to-many relationships can be queried using lookups across relationships:
>>> Article.objects.filter(publications__id=1)
, ]>
>>> Article.objects.filter(publications__pk=1)
, ]>
>>> Article.objects.filter(publications=1)
, ]>
>>> Article.objects.filter(publications=p1)
, ]>
>>> Article.objects.filter(publications__title__startswith="Science")
, ]>
>>> Article.objects.filter(publications__title__startswith="Science").distinct()
]>
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()
, ]>
>>> Article.objects.filter(publications__in=[p1,p2]).distinct()
, ]>
Reverse m2m queries are supported (i.e., starting at the table that doesn't have a ManyToManyField
):
>>> Publication.objects.filter(id=1)
]>
>>> Publication.objects.filter(pk=1)
]>
>>> Publication.objects.filter(article__headline__startswith="NASA")
, , , ]>
>>> Publication.objects.filter(article__id=1)
]>
>>> Publication.objects.filter(article__pk=1)
]>
>>> Publication.objects.filter(article=1)
]>
>>> Publication.objects.filter(article=a1)
]>
>>> Publication.objects.filter(article__in=[1,2]).distinct()
, , , ]>
>>> Publication.objects.filter(article__in=[a1,a2]).distinct()
, , , ]>
Excluding a related item works as you would expect, too (although the SQL involved is a little complex):
>>> Article.objects.exclude(publications=p2)
]>
If we delete a Publication
, its Articles
won't be able to access it:
>>> p1.delete()
>>> Publication.objects.all()
, , ]>
>>> a1 = Article.objects.get(pk=1)
>>> a1.publications.all()
If we delete an Article
, its Publications
won't be able to access it:
>>> a2.delete()
>>> Article.objects.all()
]>
>>> p2.article_set.all()
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()
]>
>>> a4.publications.all()
]>
Adding via the other end using keywords:
>>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
>>> p2.article_set.all()
, ]>
>>> a5 = p2.article_set.all()[1]
>>> a5.publications.all()
]>
Removing Publication
from an Article
:
>>> a4.publications.remove(p2)
>>> p2.article_set.all()
]>
>>> a4.publications.all()
And from the other end:
>>> p2.article_set.remove(a5)
>>> p2.article_set.all()
>>> a5.publications.all()
Relation sets can be set:
>>> a4.publications.all()
]>
>>> a4.publications.set([p3])
>>> a4.publications.all()
]>
Relation sets can be cleared:
>>> p2.article_set.clear()
>>> p2.article_set.all()
And you can clear from the other end:
>>> p2.article_set.add(a4, a5)
>>> p2.article_set.all()
, ]>
>>> a4.publications.all()
, ]>
>>> a4.publications.clear()
>>> a4.publications.all()
>>> p2.article_set.all()
]>
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()
, ]>
>>> Article.objects.all()
, , , ]>
>>> a2.publications.all()
]>
Bulk delete some articles - references to deleted objects should go:
>>> q = Article.objects.filter(headline__startswith='Django')
>>> print(q)
]>
>>> q.delete()
After the delete()
, the QuerySet
cache needs to be cleared, and the referenced objects should be gone:
>>> print(q)
>>> p1.article_set.all()
]>
除了简单的多对多关系,还有可自定义字段的多对多关系表:
其实相当于自定义一个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 models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
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)
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:
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).through_fields
as above, or a validation error will be raised.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()
]>
>>> ringo.group_set.all()
]>
>>> m2 = Membership.objects.create(person=paul, group=beatles,
... date_joined=date(1960, 8, 1),
... invite_reason="Wanted to form a band.")
>>> beatles.members.all()
, ]>
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()
, , ]>
>>> # 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()
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')
]>
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))
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 models
class 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".