Deleteting a many-to-many relation with SQLObject
If you have the need to delete an object with SQLObject you will probably like to delete a many-to-many relation some time too. First, I have to establish the relation. It’s explained in the SQLObject documentation so no details on that in this blog post. But it doesn’t say anything about how you can delete this relation. After searching the SQLObject mailing list and Wiki I finally found a clue in the source code and it’s really simple.
I am working on a website directory so I’ll just create an SQLObjectified website and an SQLObjectified category to put the website in. Categories can have many websites and websites can be placed in many categories so obviously I need a many-to-many relation. items is the module where I keep my SQLObject classes.
website = items.Website(url="http://www. .......", more="params")
category = items.Category(title="Cool category",more="params")
website.addCategory(category)
This establishes a website, a category and a relation between them. So if I want to move the website from that category I need to delete the relation between them. The magic code is
website.removeCategory(category)
That’s inserting 2 objects into a database and then creating and deleting (or should I say removing?) a relation between them in 4 simple lines of code. SQLObject surely isn’t perfect and the documentation could have been more extensive but this example demonstrates that you can do things with SQLObject in a fraction of the lines you need if you’re working with SQL.
Update : The SQLObject documentation actually says that a removeCategory method is created for this, it’s just hidden away in the reference section, under RelatedJoin: Many-to-Many.