Skip to main content

Use the Django shell

The Django shell allows administrators to query the PostgreSQL database using Django's Object Relational Mapping (ORM). This guide will discuss how to start the Django shell and show you some basic operations.

Start the Django shell

To initiate a Django shell use:

make django-shell

This will start a special session of python in the first running Gunicorn pod. If an error is encountered saying the shell cannot start, check to see if any Gunicorn pods are running with make status.

Retrieve some database objects

To get the list of all projects in a deployment, try this:

>>> from main.models import Project
>>> projects = Project.objects.all()

Now we can drill down to some media, this time filtered on the first project in the list:

>>> from main.models import Media
>>> media = Media.objects.filter(project=projects[0].id, deleted=False)

Now take a look at all the localizations and states in the first media:

>>> from main.models import Localization, State
>>> states = State.objects.filter(media=media[0].id, deleted=False)
>>> localizations = Localization.objects.filter(media=media[0].id, deleted=False)

We can see how many of each object type there is using count:

>>> num_states = states.count()
>>> num_localizations = localizations.count()

Work with users

If a user gets their account locked due to having too many password attempts, you can reset it via the shell. First query the user according to their email or username:

>>> from main.models import User
>>> user = User.get(email='')
>>> user.failed_login_count = 0

Note that users can reset passwords themselves using the password reset workflow.

We can set a user as staff using the Django shell, which gives the user access to several administration and monitoring tools:

>>> from main.models import User
>>> user = User.get(username='jdoe')
>>> user.is_staff = True

Just be careful doing this, as staff users will have administrative access to the entire deployment.

Restore deleted objects

By default, a delete request will mark objects for deletion before actually deleting them. Actual deletion occurs in a Kubernetes cron job after 30 days (by default) have passed. During this time it is possible to reverse the deletion by setting the deleted flag back to False.

>>> localizations = Localization.objects.filter(project=PROJECT_ID, deleted=True)
>>> for localization in localizations.iterator():
>>> localization.deleted = False

Alternatively, we can use bulk_update for a large number of objects.

Read more

You can read more about how to use the Django shell from the Django documentation. You can view the Tator model definitions in the source tree at main/