首页 > 数据库 >Django向数据库添加数据

Django向数据库添加数据

时间:2023-04-05 23:33:57浏览次数:34  
标签:__ question models text 数据库 Question Django 添加 import

一、添家数据到数据库

一般通过shell 命令打开Python命令行:

python manage.py shell

打开交付式命令行

>>> from pollsapp.models import Choice,Question                                   
>>> from django.utils import timezone           
>>> q = Question(question_text = "Do you like python?",pub_date = timezone.now()) 
>>> q.save()    
>>> q.question_text 
'Do you like python?'
>>> q.pub_date
datetime.datetime(2023, 4, 5, 14, 30, 27, 848158, tzinfo=datetime.timezone.utc)

证明已经成功在Question模型中添加了一条信息。

二、修改数据库数据

>>> q.question_text = "Do you like django?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

可看出只有一条数据,肯定是修改了,但看不到是什么东西,通过修改模型直观看到是什么。

三、编辑models.py中模型代码,给模型增加__str__()方法

pollsapp\models.py文件

from django.db import models
# Create your models here.
class Question(models.Model):#定义了Question模型,并继承Model类
    question_text = models.CharField(max_length=200) #创建了一个CharField类型,放问题描述字段
    pub_date = models.DateTimeField('date published')#创建了一个DateTimeField类型,放发布时间
    def __str__(self): #为Question模型增加__str__()方法。非常重要。
        return self.question_text

class Choice(models.Model):#定义了Choice模型,并继承Model类
    question = models.ForeignKey(Question,on_delete=models.CASCADE)#创建了一个问题Question类型的外键(question)字段属性
    #使用ForeignKey(外键)定义了一个关系,标识每个选项(Choice)对象都关联到一个问题(Question)对象。
    choice_text = models.CharField(max_length=200)#创建了一个CharField类型,放选择描述 字段
    votes = models.IntegerField(default=0)#创建了一个IntegerField类型,放投票数(votes)字段
    def __str__(self):
        return self.choice_text

测试(关闭shell重开就可以):

PS D:\my_pycode\MyPollsSite> python manage.py shell                  
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from pollsapp.models import Choice,Question                                   
>>> from django.utils import timezone                                             
>>> Question.objects.all()
<QuerySet [<Question: Do you like django?>, <Question: Do you like python?>]>

<Question: Do you like django?>直接显示出来了。

四、给模型添加自定义方法

给Question添加一个自定义方法,用于判断某一条“问题”数据是否是刚刚新增的。

from django.db import models
from django.utils import timezone  #时区
import datetime

# Create your models here.
class Question(models.Model):#定义了Question模型,并继承Model类
    question_text = models.CharField(max_length=200) #创建了一个CharField类型,放问题描述字段
    pub_date = models.DateTimeField('date published')#创建了一个DateTimeField类型,放发布时间
    def __str__(self): #为Question模型增加__str__()方法。非常重要。
        return self.question_text
    def was_published_recently(self): #判断某条问题信息的发布时间是否在1天之内
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

查看自定义方法使用效果:

>>> from pollsapp.models import Choice,Question
>>> Question.objects.all()                      
<QuerySet [<Question: Do you like django?>, <Question: Do you like python?>]>
>>> q=Question.objects.get(pk=1) #选择数据中的某一条
>>> q.was_published_recently() 
True

最终返回的是TRUE 自定义方法使用成功。

为了更加直观的修改数据,需要将模型添加到超级用户管理界面下,这样就可以进行可视化修改了。

标签:__,question,models,text,数据库,Question,Django,添加,import
From: https://www.cnblogs.com/light-shadow/p/17291156.html

相关文章

  • Django笔记十六之aggregate聚合操作
    本文首发于微信公众号:Hunter后端原文链接:Django笔记十六之aggregate聚合操作这一篇笔记介绍一下关于聚合的操作,aggregate。常用的聚合操作比如有平均数,总数,最大值,最小值等等用到的model如下classAuthor(models.Model):name=models.CharField(max_length=100)......
  • 流媒体技术学习笔记之(四)解决问题video.js 播放m3u8格式的文件,根据官方的文档添加vide
    源码地址:https://github.com/Tinywan/PHP_Experience总结:说明:测试环境:本测试全部来自阿里云直播和OSS存储点播以及本地服务器直播和点播播放器:VideoJs直播:1、阿里云直播,需要CDN设置HTTP头2、本地直播需要设置直播访问服务器的头部信息(本地为Nginx)add_header'Access-......
  • grafana添加仪表盘的图
    添加类似车载仪表盘的图形:[root@zabbix-server~]#grafana-clipluginslist-remote|grep-isingleid:blackmirror1-singlestat-math-panelversion:1.1.8id:grafana-singlestat-panelversion:2.0.0[root@zabbix-server~]#grafana-clipluginsinstallgrafana-single......
  • Django框架学习日记(导航)
    Django框架学习日记(导航)Django框架学习日记(一)Django框架的快速上手Django框架学习日记(二)Django框架模板相关......
  • python列表的添加的四种方式
    列表删除的五种方式python列表的增删改1、list增加元素1.1append()1.2extend()1.3insert()1.4切片1、list增加元素python中列表增加元素有四种方式:append():在列表末尾添加一个元素extend():在列表末尾添加至少一个元素insert():在列表任意位置添加一个元素切片:在列表任意位......
  • 数据库连接池
    上下文管理和SQLHelperimportpymysqlfromDBUtils.PooledDBimportPooledDBclassSqlHelper(object):def__init__(self):self.pool=PooledDB(creator=pymysql,#使用链接数据库的模块maxconnections=6,#连接池允许的最大连......
  • flask蓝图/G对象/连接数据库/
    蓝图使用中大型项目推进使用蓝图来构建文件目录1.导入蓝图类fromflaskimportBlueprint2.实例化得到蓝图对象order_bp=Blueprint('order',name)3.在app中注册蓝图app.register_blueprint(order_bp)4.在不同的views.py使用蓝图注册路由@order_bp.route('/order')目......
  • Scrapy爬虫框架 -- Mysql数据库存储数据
    一、新建一个项目scrapystartprojectmyslqst二、进入到项目目录并增加爬虫文件xiaohuacd.\myslqst\scrapygenspiderxiaohuawww.xxx.com三、修改配置文件,并开启管道存储ROBOTSTXT_OBEY=FalseLOG_LEVEL='ERROR'USER_AGENT="Mozilla/5.0(WindowsNT10.0;Win64;x64)......
  • django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error nu
    写给自己的问题备忘录django.db.utils.OperationalError:(2026,'SSLconnectionerror:unknownerrornumber')执行:pythonmanage.pymigrate报错,如下。  明明上个项目还好好的,怎么换个就不行了,网上的答案各种各种。决定从自己配置找原因,对比发现,两个环境的 mysqlclie......
  • INFS3200 先进数据库系统
    INFS3200AdvancedDatabaseSystemsPrac2:DataWarehousing(5%)Semester1,2023Duetime:4:00pm,Friday,21April2023(Week8)Submission:Submityourworkonline(INFS3200CourseWebsite)1.Introduction1.1LearningobjectivesLearnhowtocreateacubean......