Reputation: 513
I have a very simple case in which I want to run a script with python
myscript.py
:
from models import Company
c = Company(number="1234567890", name="Company name")
models.py
:
from django.db import models
class Company(models.Model):
number = models.CharField("company number", max_length=20, unique=True)
name = models.CharField("company name", max_length=30, unique=True)
class Meta:
verbose_name = "Company"
verbose_name_plural = "Companies"
I want to run python myscript.py
or something like python manage.py execute_file myscript.py
I know my question is trivial and I can import a python manage.py shell
environment, but that's not the point. Can I run it in a much simple manner?
Upvotes: 2
Views: 45
Reputation: 476594
Yes, Django has support for that: you define a custom command. It has some support for example to parse command parameters in a more convenient way.
You first need to define a file with the same name as the command you want (so here myscript.py
). This should be placed in the app/management/commands/
directory (where app
is an app of your system). So then the file tree looks like:
app/
__init__.py
management/
__init__.py
commands/
__init__.py
myscript.py
If you have not constructed any custom management commands before, you probably need to construct the files in boldface. The __init__.py
files are simply empty files.
Then your command can look like:
# app/management/commands/myscript.py
from django.core.management.base import BaseCommand
from models import Company
class Command(BaseCommand):
def handle(self, *args, **options):
c = Company(number="1234567890", name="Company name")
Note that this script is actually not doing much: you construct a Company
, but you do not store it in the database, so that means that usually the program will just stop, or raise an error in case the input is invalid.
You can then call your script with:
python3 manage.py myscript
and the command will also be listed in case you ask for help (with python3 manage.py help
).
The Django tutorial on custom commands explains in more depth what you can do to parse commands, add helptext, etc.
Upvotes: 1