---
title: "Relations plusieurs-à-plusieurs"
version: 1.9
locale: fr
source: https://docs.djangoproject.com/fr/1.9/topics/db/examples/many_to_many/
canonical: https://djangodocs.dev/fr/1.9/topics/db/examples/many_to_many/
---
# Relations plusieurs-à-plusieurs

Pour définir une relation plusieurs-à-plusieurs, utilisez un champ [`ManyToManyField`](/fr/1.9/ref/models/fields/#django.db.models.ManyToManyField).

Dans cet exemple, un `Article` peut être publié dans plusieurs objets `Publication` et une `Publication` possède plusieurs objets `Article`:

```python
from django.db import models

class Publication(models.Model):
    title = models.CharField(max_length=30)

    def __str__(self):              # __unicode__ on Python 2
        return self.title

    class Meta:
        ordering = ('title',)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)
```

Vous trouverez ci-dessous des exemples d’opérations qui peuvent être effectuées en utilisant les capacités de l’API Python. Notez que si vous utilisez [un modèle intermédiaire](/fr/1.9/topics/db/models/#intermediary-manytomany) pour une relation plusieurs-à-plusieurs, certaines des méthodes du gestionnaire connexe sont désactivées, de sorte que certains de ces exemples ne fonctionneront pas avec ces modèles.

Créez quelques `Publications`:

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

Créez un `Article`:

```pycon
>>> a1 = Article(headline='Django lets you build Web apps easily')
```

Vous ne pouvez pas le lier à une `Publication` avant qu’il ait été enregistré :

```pycon
>>> 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.
```

Enregistrez-le ! :

```pycon
>>> a1.save()
```

Associez l”`Article` à une `Publication`:

```pycon
>>> a1.publications.add(p1)
```

Créez un autre `Article` et faites-le paraître dans les deux `Publications`:

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

Ajouter une seconde fois ne pose pas problème :

```pycon
>>> a2.publications.add(p3)
```

L’ajout d’un objet du mauvais type génère une exception [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError):

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

Créez et ajoutez une `Publication` à un `Article` en une seule étape en utilisant [`create()`](/fr/1.9/ref/models/relations/#django.db.models.fields.related.RelatedManager.create):

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

Les objets Article ont accès à leurs objets `Publication` liés :

```pycon
>>> a1.publications.all()
[<Publication: The Python Journal>]
>>> a2.publications.all()
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
```

Les objets `Publication` ont accès à leurs objets `Article` liés :

```pycon
>>> p2.article_set.all()
[<Article: NASA uses Python>]
>>> p1.article_set.all()
[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
>>> Publication.objects.get(id=4).article_set.all()
[<Article: NASA uses Python>]
```

Il est possible d’interroger les relations plusieurs-à-plusieurs en utilisant des [recherches traversant les relations](/fr/1.9/topics/db/queries/#lookups-that-span-relationships):

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

>>> Article.objects.filter(publications__title__startswith="Science")
[<Article: NASA uses Python>, <Article: NASA uses Python>]

>>> Article.objects.filter(publications__title__startswith="Science").distinct()
[<Article: NASA uses Python>]
```

La fonction [`count()`](/fr/1.9/ref/models/querysets/#django.db.models.query.QuerySet.count) respecte aussi [`distinct()`](/fr/1.9/ref/models/querysets/#django.db.models.query.QuerySet.distinct):

```pycon
>>> 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: Django lets you build Web apps easily>, <Article: NASA uses Python>]
>>> Article.objects.filter(publications__in=[p1,p2]).distinct()
[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
```

Les requêtes plusieurs-à-plusieurs inverses sont possibles (c’est-à-dire des requêtes commençant par la table qui ne possède pas le champ [`ManyToManyField`](/fr/1.9/ref/models/fields/#django.db.models.ManyToManyField)) :

```pycon
>>> Publication.objects.filter(id=1)
[<Publication: The Python Journal>]
>>> Publication.objects.filter(pk=1)
[<Publication: The Python Journal>]

>>> Publication.objects.filter(article__headline__startswith="NASA")
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]

>>> Publication.objects.filter(article__id=1)
[<Publication: The Python Journal>]
>>> Publication.objects.filter(article__pk=1)
[<Publication: The Python Journal>]
>>> Publication.objects.filter(article=1)
[<Publication: The Python Journal>]
>>> Publication.objects.filter(article=a1)
[<Publication: The Python Journal>]

>>> Publication.objects.filter(article__in=[1,2]).distinct()
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
>>> Publication.objects.filter(article__in=[a1,a2]).distinct()
[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
```

L’exclusion d’un élément lié fonctionne aussi tel qu’on pourrait le prévoir (même si le code SQL sous-jacent est un peu complexe) :

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

Si nous supprimons une `Publication`, ses `Articles` ne pourront plus y accéder :

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

Si nous supprimons un `Article`, ses `Publications` ne pourront plus y accéder :

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

Ajout à partir de l”« autre côté » de la relation plusieurs-à-plusieurs :

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

Ajout à partir de l’autre côté en utilisant des mots-clés :

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

Suppression d’une `Publication` à partir d’un `Article`:

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

Et depuis l’autre côté :

```pycon
>>> p2.article_set.remove(a5)
>>> p2.article_set.all()
[]
>>> a5.publications.all()
[]
```

Les jeux de relations peuvent recevoir des valeurs. L’attribution de valeurs efface tout membre préexistant du jeu :

```pycon
>>> a4.publications.all()
[<Publication: Science News>]
>>> a4.publications = [p3]
>>> a4.publications.all()
[<Publication: Science Weekly>]
```

Les jeux de relations peuvent être effacés :

```pycon
>>> p2.article_set.clear()
>>> p2.article_set.all()
[]
```

Et l’effacement peut se faire depuis l’autre côté :

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

Recréez l”`Article` et la `Publication` que nous avons supprimés :

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

Supprimez en vrac certaines `Publications`; les références aux publications supprimées ne sont plus présentes :

```pycon
>>> Publication.objects.filter(title__startswith='Science').delete()
>>> Publication.objects.all()
[<Publication: Highlights for Children>, <Publication: The Python Journal>]
>>> Article.objects.all()
[<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()
[<Publication: The Python Journal>]
```

Supprimez en vrac certains articles ; les références aux objets supprimés ne sont plus présentes :

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

Après la suppression avec [`delete()`](/fr/1.9/ref/models/querysets/#django.db.models.query.QuerySet.delete), le cache de [`QuerySet`](/fr/1.9/ref/models/querysets/#django.db.models.query.QuerySet) doit être effacé et les objets référencés ne sont plus présents :

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

Une variante de l’appel à [`clear()`](/fr/1.9/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear) est d’attribuer un ensemble vide :

```pycon
>>> p1.article_set = []
>>> p1.article_set.all()
[]

>>> a2.publications = [p1, new_publication]
>>> a2.publications.all()
[<Publication: Highlights for Children>, <Publication: The Python Journal>]
>>> a2.publications = []
>>> a2.publications.all()
[]
```
