Django向数据库添加数据

一、添家数据到数据库

一般通过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 自定义方法使用成功。

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

posted @ 2023-04-05 23:23  老人与小孩  阅读(928)  评论(0编辑  收藏  举报