Testing Django Models on the Command Line
Using manage.py
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
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
- ↑
shellfrom django-admin and manage.py Django Documentation