Django里面集成了SQLite的數據庫,對于初期研究來說,可以用這個學習。
第一步,創建數據庫就涉及到建表等一系列的工作,在此之前,要先在cmd執行一個命令:
python manage.py migrate
這個命令就看成一個打包安裝的命令,它會根據mysite/settings.py的配置安裝一系列必要的數據庫表
第二步,我們要建立一個Model層,修改demo/model.py:
from django.db import modelsclassQuestion(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField('date published')classChoice(models.Model):question = models.ForeignKey(Question, on_delete=models.CASCADE)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)
這個Model的內容包括創建表(對象)、確定變量(字段)的類型,以及外鍵方面的信息
第三步,要激活Model,那么現在helloworld/setting.py中修改:
INSTALLED_APPS =['demo.apps.DemoConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]
主要是加了第一行的內容,這個在demo/apps下有的。目的是讓Django知道有demo這個app。
然后就在cmd下面運行:
python manage.py makemigrations demo
可以看到在demo/migrations/0001_initial.py下面生成了很多代碼
繼續run這段代碼,就完成了建表工作:
python manage.py sqlmigrate demo 0001
再跑一下migrate命令,把這些model創建到數據庫表中
python manage.py migrate
第四步,也是比較好玩的了,就是要進入到python django的shell中,執行這個命令:
python manage.py shell
在這個里面,就可以通過命令行操作數據庫了
先引入剛才創建好的model:
from demo.models importQuestion,Choice
這個命令,打印出Question所有的對象:
Question.objects.all()
然后創建一個Question的對象(或數據):
from django.utils import timezoneq =Question(question_text="What's new?", pub_date=timezone.now())q.save()q.idq.question_textq.pub_dateq.question_text = "What's up?"q.save()Question.objects.all()
第五步,然后polls/models.py中添加以下代碼:
from django.db import modelsfrom django.utils.encoding import python_2_unicode_compatible@python_2_unicode_compatible# only if you need to support Python 2classQuestion(models.Model):# ...def __str__(self):return self.question_text@python_2_unicode_compatible# only if you need to support Python 2classChoice(models.Model):# ...def __str__(self):return self.choice_textimport datetimefrom django.db import modelsfrom django.utils import timezoneclassQuestion(models.Model):# ...def was_published_recently(self):return self.pub_date >= timezone.now()- datetime.timedelta(days=1)
新聞熱點
疑難解答