Django教程——01安装使用Django教程——02连接初始化数据库,今天小编就来说说关于django怎么直接使用数据库?下面更多详细答案一起来看看吧!
django怎么直接使用数据库
Django教程——01安装使用
Django教程——02连接初始化数据库
接着上文连接好数据库后,下面讲下如何通过Django将工程里实体对象生成数据库表
一、定义实体
在polls应用下创建数据库实体
其中Django数据库字段属性设置教程 https://docs.djangoproject.com/en/4.0/ref/models/fields/ Model field reference | Django documentation | Django
polls/models.py
from django.db import models
# Create your models here.
class Question(models.Model):
question_text=models.CharField(max_length=200)
pub_date=models.DateTimeField('date published')
def __str__(self):
return self.question_text
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
二、使用实体对象
1、在项目settings.py里引入应用
mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
2、初始化模型对象
python manage.py makemigrations polls
执行该命令后,就会在polls/migrations/0001_initial.py文件下生成实体对象代码,用于生成数据库表用
3、生成建表sql
python manage.py sqlmigrate polls 0001
执行结果如下
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL,
"question_id" integer NOT NULL
);
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
4、同步建表语句到数据库
python manage.py migrate
执行完后,数据库就会增加上面两张表
三、shell操作
执行shell命令
python manage.py shell
就可以通过控制台进行编写调用模型的api
>>> from polls.models import Choice, Question # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID.
>>> q.id