Testing Django Models on the Command Line: Difference between revisions

From Littledamien Wiki
Jump to navigation Jump to search
(Created page with "Category:Django Category:Python Category:Web Development First, `cd` to the project directory. Make sure the `DJANGO_SETTINGS_MODULE` environment variable is set....")
 
No edit summary
 
Line 1: Line 1:
[[Category:Django]] [[Category:Python]] [[Category:Web Development]]
[[Category:Django]] [[Category:Python]] [[Category:Web Development]]
== Using `manage.py` ==
From the command line in the root directory of the Django project:
<syntaxhighlight lang="bash">
$python manage.py shell
</syntaxhighlight>
Then it's possible to import objects from the project's packages without having to concern yourself with environment variables like `DJANGO_SETTINGS_MODULES`.<ref>[https://docs.djangoproject.com/es/1.9/ref/django-admin/#shell `shell` from django-admin and manage.py] Django Documentation</ref>
<syntaxhighlight lang="python">
>>> 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
</syntaxhighlight>
== Alternate method ==
First, `cd` to the project directory.
First, `cd` to the project directory.


Line 31: Line 50:
not found.
not found.
</syntaxhighlight>
</syntaxhighlight>
== Notes ==
<references />

Latest revision as of 00:22, 4 February 2016

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]