# dokumentasi Django 2.0.8

# Hubungan banyak-ke-banyak

Untuk menentukan hubungan many-to-many, gunakan `ManyToManyField`.

Dalam contoh ini, sebuah `Article` dapat diterbitkan dalam banyak obyek `Publication`, dan sebuah `Publication` mempunyai banyak obyek `Article`:

    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',)

Berikut ini adalah contoh-contoh dari tindakan yang dapat dilakukan menggunakan fasilitas API Python. Catat bahwa jika anda sedang menggunakan an intermediate model untuk hubungan many-to-many, beberapa dari metode pengelola terkait ditiadakan, jadi beberapa dari contoh-contoh ini tidak akan bekerja dengan model-model seperti itu.

Buat sepasang `Publications`:

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

Buat sebuah `Artikel`:

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

Anda tidak dapat mengkaitkan itu dengan `Publication` sampai itu telah disimpan:

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

Simpan itu!

    >>> a1.save()

Kaitkan `Article` dengan `Publication`:

    >>> a1.publications.add(p1)

Buat `Article` lain, dan setel itu untuk muncul di kedua `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)

Menambahkan sebuah obyek dari jenis salah memunculkan `TypeError`:

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

Buat dan tambah sebuah `Publication` pada sebuah `Article` di satu langkah menggunakan `create()`:

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

Obyek `Article` telah mengakses ke obyek `Publication` terhubung mereka:

    >>> 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>]>

Obyek `Publication` telah mengakses ke obyek `Article` terhubung mereka:

    >>> 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>]>

Hubungan many-to-many dapat diminta menggunakan 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>]>

Fungsi `count()` menghormati `distinct()` juga:

    >>> 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>]>

Membalikkan permintaan m2m didukung (yaitu, dimulai pada tabel yang tidak mempunyai sebuah `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>]>

Tidak termasuk barang terkait bekerja ketika anda akan mengharapkan, terlalu (meskipun SQL terlibat adalah sedikit rumit):

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

Jika kami menghapus `Publication`, `Articles` nya tidak akan dapat mengaksesnya:

    >>> 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 []>

Jika kami menghapus sebuah `Article`, `Publications` nya tidak akan dapat mengakses itu:

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

Menambahkan melalui akhiran 'other' dari sebuah 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>]>

Menambahkan melalui akhiran lain menggunakan kata kunci:

    >>> 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>]>

Memindahkan `Publication` dari sebuah `Article`:

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

Dan dari akhiran lain:

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

Kumpulan hbungan dapat disetel:

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

Kumpulan hubungan dapat dibersihkan:

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

Dan anda dapat membersihkan dari akhiran lain:

    >>> 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>]>

Membuat kembali `Article` dan `Publication` kami telah hapus:

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

Menghapus massal beberaoa `Publications` - acuan pada untuk menghapus penerbitan harus pergi:

    >>> 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>]>

Menghapus massal beberapa artikel - acuan pada menghapus obyek harus pergi:

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

Setelah `delete()`, cache `QuerySet` butuh dibersihkan, obyek acuan harus hilang:

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