Testing Django Models on the Command Line

From Littledamien Wiki
Revision as of 00:22, 4 February 2016 by Video8 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Using manage.py[edit]

From the command line in the root directory of the Django project:

$python manage.py shell

Then it's possible to import objects from the project's packages without having to concern yourself with environment variables like DJANGO_SETTINGS_MODULES.[1]

>>> from clients.models import Client
>>> c1 = Client.objects.get(pk=1)
>>> c1.name
North Rose Devs
>>> clients = [{'id':c.id, 'name':c.name} for c in Client.objects.all()]
>>> clients

Alternate method[edit]

First, cd to the project directory.

Make sure the DJANGO_SETTINGS_MODULE environment variable is set. (See Setting Environment Variables in Powershell.)

Set DJANGO_SETTINGS_MODULE to the path to settings.py in the Django project that is being tested. E.g.:

> $env:DJANGO_SETTINGS_MODULE = 'myproject.settings'

Start up python cli:

> python

Example of fetching a model:

>>> from clients.models import Client
>>> from contact_info.models import Address
>>> c1 = Client.objects.get(pk=1)
>>> c1.name
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
...     c2 = Client.objects.get(pk=1,display_on_frontend=True)
... except ObjectDoesNotExist:
...     print('not found.')
...
not found.

Notes[edit]