models.py
# consider Author & Book model
class Author(models.Model):
name = models.CharField(max_length=200)
class Book(models.Model):
authors = models.ManyToManyField(Author, related_name='books')
title = models.CharField(max_length=200)
desc = models.TextField()
Here, we assume that a book have many author & a authors have many book.
book (M) <------> (M) author
- now, we find
a book all authors
& some operations
books = Book.objects.all()
if len(books) > 0:
book = books[0]
# first book all authors
first_book_all_authors = book.authors.all()
# clear/remove all authors | (not same as delete)
book.authors.clear()
# add a author
new_author = Author.objects.create(name = "Author name: Jhon smith")
book.authors.add(new_author)
# add multiple author
all_authors = Author.objects.all()
book.authors.set(all_authors)
# remove a author
auth1 = Author.objects.filter(pk = 1).first()
book.authors.remove(auth1) # if auth1 is not None, then it's remove this author
- now, you find
a author all books
& some operations
authors = Author.objects.all()
if len(authors) > 0:
auth = authors[0]
# first author all book
first_author_all_books1 = auth.books.all() # if set related field name | related_name='books'
first_author_all_books2 = auth.book_set.all() # if not set related field name | 'modelName'_set.all()
# clear/remove all books | (not same as delete)
auth.books.clear()
# add a book
new_book = Book.objects.create(title = "new book", desc="book desc")
auth.books.add(new_book)
# add multiple book
all_books = Book.objects.all()
auth.books.set(all_books)
# remove a book
book = Author.objects.filter(pk = 1).first()
auth.books.remove(book) # if book is not None, then it's remove this book
NB: THINK SIMPLY