How to update multiple objects at once, many-to-many field

The docs have a nice example of how to update multiple objects:
# Update all the headlines with pub_date in 2007.
Entry.objects.filter(pub_date__year=2007).update(headline=‘Everything is the same’)
But, as noted, this does not work with m2m fields.

Currently, I can loop through a filtered queryset to remove related objects from a many-to-many field (here, ‘assigned_readers’):
inbox_entries = Submission.objects.filter(inbox=inbox).all()
for each in inbox_entries:
each.assigned_readers.clear()
This works, but… can’t be an efficient way to do it. I’d love to be able clear a many-to-many field using something like the above syntax:
Submission.objects.filter(inbox=inbox).update(assigned_readers=None)
Can anyone point me to an example / description of how to update multiple objects at once, with a many-to-many field?

When you’re talking about a many-to-many field, remember that there are three tables involved - the two tables related to each other and the third table joining the two.

This means that when you’re talking about “updating” a many-to-many relationship, there are actually two different events to discuss.

  • First, there’s the simple assignment / removal, which is what I think you’re talking about here. I believe it’s the clear() method you’re looking for.

You wrote:

I’m wondering why you would think that? Again, keep in mind that removing a relationship from between both ends of a many-to-many does not involve a change to either of the two ends of that relationship. All that is happening is that the row in the join table is being deleted.

  • Then, there’s the making of changes across the relationship, and that’s where you’ll want to use the _set notation to identify a queryset containing the related items to modify.

In either case, you might want to spend some time with the Many-To-Many Relationships docs, reading through the examples to see what features are available and how to use them.

(Note: I could be more specific if you were to post your actual models involved here, so that we could continue this discussion in the context of the models you’re using rather than trying to address this in the abstract or making reference to the examples in the documentation.)

Ken

Thanks, Ken. Maybe I’m prematurely guessing that a loop will slow things down here.