Given these two Models:
class Item(models.Model):
timestamp = models.DateTimeField()
class Source(models.Model):
items = models.ManyToManyField(Item, related_name="sources")
I can find all of a Source's Items before a given time using this:
source.items.filter(timestamp__lte=some_datetime)
How do I efficiently remove all of the items that match that query? I suppose I could try something like this:
items_to_remove = list(source.items.filter(timestamp__lte=some_datetime))
source.items.remove(*items_to_remove)
but that seems bad.
Note that I do not want to delete these items, since they may also belong to other Sources. I just want to remove their relationship with the specific source.
I think you got it right on the money, except you don't need to convert to a list.
The
remove
/add
method looks like the followingand the docs http://www.djangoproject.com/documentation/models/many_to_many/ use add multiple examples in the form of
[p1, p2, p3]
so I'd wager the same goes forremove
, seeing as the arguments are the same.Digging in a little more, the remove function iterates over
*objs
one by one, checking if it's of the valid model, otherwise using the values as PK's, then deletes the items with apk__in
, so I'm gonna say yes, the best way is to query your m2m table first for objects to delete then pass in those objects into the m2m manager.