如何删除所有的关系从许多?

在一个模型中,我有这个:

class MyModel(models.Model):
relations = models.ManyToManyField(OtherModel)
....

如果我选择:

my_object.relations.remove(other_model_object)

很管用。

如何从关系中删除所有对象? my_object.relations.clean()不工作。

78727 次浏览

首先,您需要通过使用. clear ()或. remove ()来清除关系,使用更适合您需要的 根据文件记录

之后,您需要使用[ YourModel ] . 删除()方法删除对象。

如果您只需要删除2个模型之间的所有实例的关系,那么您可以通过访问关系表的 Manager 来做到这一点。M2m 关系表可以通过 MyModel.relations.through访问,因此删除关系变得很容易:

MyModel.relations.through.objects.all().delete()

参考文献:

Https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models

要删除 所有相关对象而不删除它们,只需使用:

my_object.relations.remove(*my_object.relations.all())

使用 my_object.relations.clear()

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()

在这里,我们假设一本书有许多作者和一个作者有许多书。

书(M) < —— > (M)作者

  1. 现在,我们找到 a book all authors和一些操作
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
  1. 现在,你找到 a author all books和一些操作
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
    

注意: 简单思考