How to update manytomany field in Django?

后端 未结 3 1797
一个人的身影
一个人的身影 2020-12-05 05:11

Here\'s an example:

If I have these classes

class Author(models.Model):
    name = models.CharField(max_length=45)

class Book(models.Model):
    nam         


        
3条回答
  •  北海茫月
    2020-12-05 05:57

    With the auto-generated through table, you can do a two-step insert and delete, which is nice for readability.

    george = Author.objects.get(name='George')
    georfe = Author.objects.get(name='Georfe')
    
    book.authors.add(george)
    book.authors.remove(georfe)
    assert george in book.authors
    

    If you have an explicitly defined through table (authors = models.ManyToManyField(Author, through=BookAuthors) then you can change the relationship explicitly on BookAuthor. A little known fact is that this Model already exists, it is generated by django automatically. Usually you should only create an explicit through model if you have extra data you wish to store (for instance the chapters a particular author wrote, in a multi-author book).

    # This line is only needed without a custom through model.
    BookAuthor = Book.authors.through
    book_author = BookAuthor.objects.get(author=georfe, book=great_american_novel)
    book_author.author = george
    book_author.save()
    assert george in book.authors
    

提交回复
热议问题