Quantcast
Channel: Bulk update for many to many fields - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Bulk update for many to many fields

$
0
0

I have two models as Follows:

class Book(models.Model):    title = models.CharField(max_length=100)    year = models.IntegerField(max_lenght=4)    author = models.ManyToManyField(null=true, blank=true)class Author(models.CustomUser):    # some fields

Now, what I am looking to do is add an Author to multiple Book objects without iterating over the list of book objects.

Django's update method does not support ManyToManyField as per docs. It says:

You can only set non-relation fields and ForeignKey fields using this method. To update a non-relation field, provide the new value as a constant. To update ForeignKey fields, set the new value to be the new model instance you want to point to.

So currently I am doing the following which is highly inefficient as I'll be hitting the database for each book object.

author = Author.objects.get(pk=1)books = Book.objects.filter(**kwargs) # say this returns 100 objects# each loop here will hit the database making it really inefficient# for long lists.for book in books:    book.authors.add(author)    book.save()

I am pretty sure there is a way around this, but I am just not able to find it in the documentation.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>