Python Shell 解释器下使用Django Model

本文介绍如何在Django项目中直接操作模型数据,包括添加、获取和删除数据等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

转载于:https://www.cnblogs.com/qinfengxiaoyue/p/4057090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值