How to remove all relations from manytomany?
In one model, I have this:
class MyModel(models.Model):
relations = models.ManyToManyField(OtherModel)
....
and if I choose:
my_object.relations.remove(other_model_object)
it works.
How to remove all objects from the relations? my_object.relations.clean()
is not working.
First, you'll need to clear the relationship(s) by using .clear() or .remove(), whichever suits your needs better according to the docs.
After that, you'll need to delete the object(s) by using the [YourModel].delete() method.
If you need to delete only the relationship for all instance between 2 models then you can do that by accessing the Manager of the relationship table. The m2m relationship table can be accessed via MyModel.relations.through
so for deleting the relationships it becomes easy:
MyModel.relations.through.objects.all().delete()
reference:
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through
Use my_object.relations.clear()
To remove all related objects without deleting them, just use:
my_object.relations.remove(*my_object.relations.all())
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