Reputation: 15
I was wondering how one can exercise the models outside the Django
manage.py
control.
i.e. given the following combination of the tutorial parts how would I be able to just python models.py
.
# models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
if __name__ == "__main__":
from polls.models import Poll, Choice
print Poll.objects.all()
import datetime
p = Poll(question="What's up?", pub_date=datetime.datetime.now())
p.save()
print p.id
print p.question
print p.pub_date
p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
p.save()
print Poll.objects.all()
I tried setting up os.environ['DJANGO_SETTINGS_MODULE'] = ...
to my settings file, no joy.
and then changed that to be this at the top
import imp
imp.find_module('settings') # Assumed to be in the same directory.
from django.core.management import setup_environ
import settings
setup_environ(settings)
but to no avail.
Any ideas would be grateful received it seems such a typical use case.
I appreciate that Django has a big ecosystem behind it but I was expecting some form of:
set-up-env
do-stuff
without the need to write mange scripts.
Upvotes: 1
Views: 1469
Reputation: 347
run this from project root dir :- it works :D
import os
import sys
from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)) + '/../')
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Meta:
app_label = #app_name
your second class
if __name__ == "__main__":
print Poll.objects.all()
import datetime
p = Poll(question="What's up?", pub_date=datetime.datetime.now())
p.save()
print p.id
print p.question
print p.pub_date
p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
p.save()
print Poll.objects.all()
Upvotes: 1