How to update manytomany field in Django?

后端 未结 3 1806
一个人的身影
一个人的身影 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

    Note: This code will delete the bad 'georfe' author, as well as updating the books to point to the correct author. If you don't want to do that, then use .remove() as @jcdyer's answer mentions.

    Can you do something like this?

    george_author = Author.objects.get(name="George")
    for book in Book.objects.filter(authors__name="Georfe"):
        book.authors.add(george_author.id)
        book.authors.filter(name="Georfe").delete()
    

    I suspect that this would be easier if you had an explicit table joining the two models (with the "through" keyword arg) -- in that case, you would have access to the relationship table directly, and could just do a .update(id=george_author.id) on it.

提交回复
热议问题