django之数据增删改查

一、进入shell界面命令如下

python manage.py shell

二、进行引用命令

 from polls.models import *

 数据的查询命令如下

 a=Question.objects.all()
 a[0].question_text

 

 数据的添加命令如下

调用模块

 from django.utils import timezone

添加数据

 q = Question(question_text="What's new?", pub_date=timezone.now())

保存

 q.save()

数据添加还可以

q=Question()#定义q
q.question_text="hello"   #添加数据
q.pub_date=timezone.now()
 q.save()#保存

给模型增加方法

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):#增加的方法
        return self.question_text

 可以直接使用以下命令查询

Question.objects.all()

条件查询

Question.objects.filter(id=1)#id=1为条件

 查询有没有某条数据,没有就加入该数据

 d=dict(question_text='你在家吗?',pub_date='2009-5-11')
q=Question.objects.get_or_create(**d)#**d为固定格式 ,d为上句命令的变量名

 再次运行

 修改数据

方法一

 a=Question.objects.get(id=5)
a.question_text='今天几'#要修改的内容
 a.save()#保存

 方法二

 t=Question.objects.filter(id=5).update(question_text='男装')

 方法三

d=dict(question_text='wang')
 t=Question.objects.filter(id=6).update(**d)

 数据加10

from django.db.models import F
 t=Question.objects.filter(id=1)
 t.update(id=F('id')+10)

删除数据

删除一条数据

 Question.objects.get(id=1).delete()

 删除多条数据

 Question.objects.filter(question_text='wang').delete()

 删除全部数据

 Question.objects.all().delete()

多表查询

 q=Question.objects.get(id=1)#在父表中确定一个数据

 q.choice_set.all()#查询子表中与父表中确定的数据

原文地址:https://www.cnblogs.com/wbf980728/p/14170221.html