I was wondering if there is the equivalent of a "add all" or "bulk create" for many to many relationships which reduce the number of queries (I will be doing this for a long list)?
The docs on this subject seem to suggest that this is not possible:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
**Associate the Article with a Publication:**
a1.publications.add(p1)
**Create another Article, and set it to appear in both Publications:**
a2 = Article(headline='NASA uses Python')
a2.save()
a2.publications.add(p1, p2)
a2.publications.add(p3)
If you want to add queryset to bulk add or remove method of many to many relation models :
qs = Article.objects.all()
publications = Publications.objects.get(id=1)
publications.article_set.add(*qs)
publications.save()
publications.article_set.remove(*qs)
publications.save()
Of course it's possible! You just have to create an explicit intermediate table and
then use this model's bulk_create
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With