Excecuting methods within a Django project context? - Django
I need to execute e few methods within my Django project's context, in order to work wi开发者_运维百科th Models.
I know commands exists, but I would like to import these methods and execute them within Python code.
Any ideas?
You only need to set your PYTHONPATH and DJANGO_SETTINGS_MODULE environment variables prior to calling the python interpreter. From then on you can import your models, call their methods, etc...
export PYTHONPATH="...include your site's apps path..."
export DJANGO_SETTINGS_MODULE="mysite.settings"
python
>>> from myapp.models import MyModel
>>> MyModel.objects.all()
...
Most of my commandline (and cron) scripts look something like:
#!/usr/bin/env python
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db import transaction
... code ...
# you need to do the followng before exit if you did any DB changes.
transaction.commit_unless_managed()
Update for comments:
If you have made any saves/other changes, then my (possibly somewhat out of date) answer is Yes. I don't know if it is still required in the latest-stable release, but I'm sort of a belt-and-suspenders person when it comes to my database. I see transaction.commit_unless_managed()
at the end of my scripts as a sort of safety net: If managed mode is in effect then it is a NOP, if it isn't then this makes sure the commit happens.
精彩评论