Wilcox Development Solutions Blog

Using Fabric to import your Django models

December 22, 2011

A client wants me to write an import task for their Django app. They already use Fabric to deploy their site, so I figured that writing this script as a Fabfile would work out well.

The script requires me to import classes from their Django app. Specifically, I’m doing queries against their domain models, and adding things to the database, and I’d like to reuse the Django ORM classes already defined.

I finally got it working, but it was non-obvious. Here’s how I did it.

Setting up the module import path

In this project all the fabfiles go in a folder named “fab” in the Django project’s directory. So, I need to tell Python to look outside the fab folder for what it is trying to import.

But that’s not enough - I also need to import the Django project by name, so I need to go one more folder out (to the parent folder of the Django project).

Actually importing the Django models

the django.project nonsense is to set up an environmental variable (pointing to the settings.py file) - Django requires this variable to be set, and will error without it.

Next we import the Django project, and start using entities from an app inside it.

Easy, Huh?


Tagged with:

Written by Ryan Wilcox Chief Developer, Wilcox Development Solutions... and other things