django的shell命令,如何操作数据库读写数据?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文中,苏南大叔描述一下django的shell命令。其实shell仅仅是个手段,苏南大叔认为主要内容在于可以预览一下django如何操作数据库。在python的世界里面,比如苏南大叔描述过的scrapy等,动不动就会拿出shell调试说事,这一点上,让苏南大叔觉得挺不习惯的。不过,shell操作就是python的一大特色。习惯就好习惯就好。

本文测试环境:mac,python@3.7.4,django@2.2.4。本文中的特约嘉宾还是官方的polls应用。
模型定义
首先回顾一下polls的模型定义,polls/models.py文件里面的定义,和本文的内容息息相关。
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text更多详细内容,请参考:
打开shell界面
下面的是打开django的shell界面的方式方法,需要注意的是。执行命令的位置,需要在manage.py这一层上执行命令:
python manage.py shell这个命令的执行界面和python的shell基本上非常像,但是里面可以识别django的特有函数功能等。截图如下:

数据库操作(增删改查)
通过这种shell命令行的方式,执行增删改查,并不是苏南大叔所推荐的。这里仅作为体验项目进行描述。
引入基本类库
from polls.models import Choice, Question
from django.utils import timezone
查询所有数据
Question.objects.all()
插入新数据
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()查看插入的新数据的字段
q.id
q.question_text
q.pub_date
修改数据
q.question_text = "What's up?"
q.save()普通数据查询
Question.objects.filter(id=1)Question.objects.filter(question_text__startswith='What')current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)Question.objects.get(id=2)删除数据
q.delete()特殊数据查询
q = Question.objects.get(pk=1)
q.was_published_recently()q.choice_set.all()
q.choice_set.count()Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.filter(choice_text__startswith='Just hacking')特殊数据插入
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)相关链接
总结
本文中,苏南大叔以介绍django的shell命令为引子,引出了django中的模型数据的增删改查的例子。在shell中写代码,和在普通的.py文件中写代码,基本上是差不多的。所以,本文虽然不是太重要,但是对后面的文章,也是有一定的借鉴意义的。
更多django相关博客文章,请点击苏南大叔的博客: