码迷,mamicode.com
首页 > 编程语言 > 详细

Python Shell 解释器下使用Django Model

时间:2014-10-28 17:24:22      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:http   io   os   ar   使用   strong   on   art   amp   

sys.path.append(‘E:/Projects/DjangoProjects/myFirstSite‘)

os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘myFirstSite.settings‘)

from books.models import *

print (Author.objects.all())

 

 

 

如下(http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell):

Since Django 1.4 you should avoid using setup_environ(settings) (post by Melug) because it is deprecated. Use the following instead and you will be able to access your model

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# your imports, e.g. Django models
from your_project_name.models import Location

# From now onwards start your script..

Here is an example to access and modify your model:

if __name__ == ‘__main__‘:    
    # e.g. add a new location
    l = Location()
    l.name = ‘Berlin‘
    l.save()

    # this is an example to access your model
    locations = Location.objects.all()
    print locations

    # e.g. delete the location
    berlin = Location.objects.filter(name=‘Berlin‘)
    print berlin
    berlin.delete()

 

 

Example model:

class Location(models.Model):
    name = models.CharField(max_length=100)

Python Shell 解释器下使用Django Model

标签:http   io   os   ar   使用   strong   on   art   amp   

原文地址:http://www.cnblogs.com/qinfengxiaoyue/p/4057090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!