Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a Django model into a python cli script

I am just getting this django app (also an inexperienced python user) running and wanted to be able to access the models.

I have the following:

import sys, os
sys.path.append('/Users/jx/dev/arc/django/second/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from django.db import models
from testproject.models import Location
loc=Location.objects.get(name='Joes')

print loc.name

but get the following error:

Traceback (most recent call last):
  File "zz.py", line 6, in <module>
    from testproject.models import Location
ImportError: No module named testproject.models

Is there a way I can determine whether it is loading the settings.py correctly? Or is there an obvious syntax issue? Should the PYTHONPATH reflect the locations for the models (it currently doesn't if print os.environ)?

thx

like image 262
timpone Avatar asked Nov 19 '25 08:11

timpone


1 Answers

Django has support for creating custom django-admin commands (documentation).

Very useful for creating command line scripts that access the model.

like image 89
codeape Avatar answered Nov 21 '25 21:11

codeape



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!