MySQL Composite Indexing for Django

Posted my first Django snippet! This concerns a quick and dirty hack for getting composite indexing in MySQL. It’s also a simple example of how to use Django’s post_syncdb signal.

Django currently comes with a unique_together meta attribute you can use to specify unique combinations of fields. I think the backends create an index in the database from this. However, I couldn’t find anything for simply creating non-unique attributes, hence the hack you see in the snippet.

I don’t really have the patience to make it work fully for the other backends since I don’t use them currently (aside from SQLite3 for testing), but it’s GoodEnoughForMe.

Saving keystrokes

Happiness comes from small victories. In order to save on unnecessary typing, I’ve made a few shortcuts in Django for my most common “python” commands.

For example, my test command is longer than most because I use a different settings file for tests to keep the environments separate. So I popped open an editor and created this:

python test $* –settings=settings_test

Save as something short — like ‘ts’, then make executable

chmod u+x ts

Now instead of typing python test … , I can simply type ./ts and be done with it. Note that things like ./ts my_app also still work

Last step: update your repository to ignore these files so you don’t accidentally piss off any others you’re working with.