Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

python - How to update manytomany field in Django?

Here's an example:

If I have these classes

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

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

In the database I have one Author with the name "George" and another one with the name "Georfe". The last one is a mistake. So what I want is in every Book that have "Georfe" as one of his Author replace it by the Author "George".

In SQL is really easy to do. If id of "George" = 3 and id of "Georfe" = 7 and the relation table name is "author_book":

UPDATE author_book SET id=3 WHERE id=7;

Is it possible to do that with the Django ORM?

I found a way to do it: I loop trough all the related Books of the mistyped author and do:

book.authors.add(Author.objects.get(id=3))
book.authors.remove(Author.objects.get(id=7))

But I don't find this solution really elegant and efficient. Is there a solution without the loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...