Reputation: 716
I want to remove large sets of objects from a m2m relation. Therefore I do at the moment a simple loop:
objs = Foobar.objects.filter(to_remove=1)
for obj in objs:
rel_foobar.remove(obj)
Is there a faster alternative because this needs very long to execute?
rel_foobar = models.ManyToManyField(Foobar)
Upvotes: 0
Views: 53
Reputation: 1292
You can unpack the QuerySet in the call to remove. You can do this leveraging the reverse query ability of M2M fields in Django.
Get the object that you are removing the objects off of (the one that rel_foobar is a field on):
objs = Foobar.objects.get(to_remove=1)
container = Container.objects.get(id=1)
container.rel_foobar.remove(*objs)
Upvotes: 1