Python Shell 解释器下使用Django Model
sys.path.append(‘E:/Projects/DjangoProjects/myFirstSite‘)
os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘myFirstSite.settings‘)
from books.models import *
print (Author.objects.all())
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)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。