Created by dan on Friday 15th January, 2010 at 6:38 PM
Tags: Django, MongoDB, Python, Web development
I've got to the point where I have a table containing all entries from a set Mongo collection. They each have a checkbox beside them with the value of '_id' where I can select them for a magical journey in to the mass deletion/modification abilities of the associated Django view. The problem I find myself with, after trying to figure out how to make use of the '_id' in Django templates in the first place, is then iterating through them for removal (or whatever).
Of course, I'm using the Django getlist() method to find all posted '_id' values, however PyMongo gets a little fussy here, and it specifically wants ObjectId's, so then I found the best (and simplest) way to solve the issue is to iterate through each item returned by the getlist() method and convert each to an ObjectId object.
First of all, import the ObjectId method...
from pymongo.objectid import ObjectId
Then, iterate through the posted checkboxes using an inline for loop on the getlist() method, like so:
records = [ObjectId(str(record)) for record in request.POST.getlist('massaction')]
Finally, to remove (for example), just do this:
MyCollection.remove({'_id': {'$in': records}})
Simples.