Skip to content

Instantly share code, notes, and snippets.

@eclecticmiraclecat
Last active November 6, 2020 10:10
Show Gist options
  • Save eclecticmiraclecat/0a45fd5bc4a6144a1ac006b6107e1948 to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/0a45fd5bc4a6144a1ac006b6107e1948 to your computer and use it in GitHub Desktop.

many to many

  • many author can write many books
# models..py
class Author(models.Model):
  name = models.CharField(max_length=20)

class Book(models.Model):
  title = models.CharField(max_length=20)
  authors = models.ManyToManyField(Author
>>> from cbvApp.models import Author, Book
>>> a = Author(name='bob')
>>> a.save()
>>> b = Author(name='jack')
>>> b.save()
>>> a.book_set.create(title='the begins')
<Book: Book object (1)>
>>> b.book_set.create(title='the begins')
<Book: Book object (2)>
Author
+----+------+
| id | name |
+----+------+
|  1 | bob  |
|  2 | jack |
+----+------+

Book
+----+------------+
| id | title      |
+----+------------+
|  1 | the begins |
|  2 | the begins |
+----+------------+

book_authors
+----+---------+-----------+
| id | book_id | author_id |
+----+---------+-----------+
|  1 |       1 |         1 |
|  2 |       2 |         2 |
+----+---------+-----------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment