Django Without the Web

One of the things I like best about Django is how easy its ORM makes it to work with databases. Too bad Django is only for web applications. Sure, you could deploy a Django app and then make use of it from a non-web application using a REST API, but that would be too awkward.

But there is an easy way to use Django without the web! Here's the trick - write your application as Django management commands. Then you can run it from the command line. Just like ' syncdb' or ' migrate', you can run ' my_own_application' and your application has access to the full power of Django ORM.

Adding a new Django management command is surprisingly easy:

  1. Add a management/commands directory to your application.
  2. Create a file containing a class that extends or a subclass.
  3. Write a handle method that runs your application
  4. Run ' anything'

Here's an example of a trivial command:

from import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        print "Hello, world"

Create a management/commands directory in your application and save this there as ''.

Now try it:

$ ./ hello
Hello, world

How about doing something useful?  Here's an example that prints out all of your invoices, so you can see how easy it is to access your data:

from import BaseCommand
from appname.models import Invoice

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        print "Invoices"
        for invoice in Invoice.objects.order_by('date'):
            print u"%s %s" % (, invoice.summary)

I've used custom management commands to do things like importing data where something more complicated than loading a fixture was needed.

For more details, see the Django documentation.

New Call-to-action
blog comments powered by Disqus



You're already subscribed