Django学习记录_Part2

  • 数据库安装

  Django默认使用SQLite,且SQLite包含在python中。要使用其他的数据库,可以在mysite/settings.py中修改配置。

  Django中的默认配置:

1 DATABASES = {
2     'default': {
3         'ENGINE': 'django.db.backends.sqlite3',
4         'NAME': BASE_DIR / 'db.sqlite3',
5     }
6 }

  其中,‘ENGINE’可修改成其他数据库,如:

  1. 'django.db.backends.postgresql'
  2. 'django.db.backends.mysql'
  3. 'django.db.backends.oracle'
  4. 其他

  ‘NAME’是数据库的名字,使用SQLite的话,默认会在你的项目目录下生成一个数据库文件‘db.sqlite3’。

  如果使用其他数据库,还需要设置如下配置:

  1. ‘USER’
  2. 'PASSWORD'
  3. 'HOST'
  • 设置时区

  在mysite/settings.py中设置‘TIME_ZONE’为想要设置的时区。

  如:TIME_ZONE = 'Asia/Shanghai'

 

  • 使用mysite/settings.py中的‘INSTALLED_APPS‘中的apps前,需要先创建表

  输入:python manage.py migrate

 

  • 创建模型(model)

  编辑‘polls/models.py’文件

 1 from django.db import models
 2 
 3 
 4 class Question(models.Model):
 5     question_text = models.CharField(max_length=200)
 6     pub_date = models.DateTimeField('date published')
 7 
 8 
 9 class Choice(models.Model):
10     question = models.ForeignKey(Question, on_delete=models.CASCADE)
11     choice_text = models.CharField(max_length=200)
12     votes = models.IntegerField(default=0)
  • 激活模型

  输入:python manage.py makemigrations polls

  会看到类似以下输出:

Migrations for 'polls':
      polls/migrations/0001_initial.py
        - Create model Question
        - Create model Choice

  输入: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;
  • 在数据库中创建模型

   输入:python manage.py migrate

  会看到类似以下输出:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK
  • 改变模型的三个步骤
  1. 在“models.py”中修改你的模型;
  2. 运行命令:python manage.py makemigrations,为你的修改创建migration;
  3. 运行命令:python manage.py migrate,应用修改到数据库中。
  • 使用Django提供的python shell

  运行命令:python manage.py shell

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

# 数据库里目前Question数据为空.
>>> Question.objects.all()
<QuerySet []>

# 创建一个新的Question.
# 由于在settings文件里启用了支持时区, 所以需要为pub_date提供一个带有tzinfo信息的时间。
# 使用timezone.now()方法,而不是datetime.datetime.now().
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# 保存对象到数据库. 使用save()方法.
>>> q.save()

# Now it has an ID.
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()

# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

“<Question: Question object (1)>”不是一个很好的对象表达方式,我们可以修改“Question”模型,添加一个“~django.db.models.Model.__str__”方法给“Question”和“Choice”模型,修改“polls/models.py”文件:

 1 from django.db import models
 2 
 3 class Question(models.Model):
 4     # ...
 5     def __str__(self):
 6         return self.question_text
 7 
 8 class Choice(models.Model):
 9     # ...
10     def __str__(self):
11         return self.choice_text

让我们为“Question”模型再添加一个方法:

 1 import datetime
 2 
 3 from django.db import models
 4 from django.utils import timezone
 5 
 6 
 7 class Question(models.Model):
 8     # ...
 9     def was_published_recently(self):
10         return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

保存这些修改,运行命令“python manage.py shell”开启一个新的python shell界面:

>>> from polls.models import Choice, Question

# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>

# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
  • 创建管理员

  运行命令:python manage.py createsuperuser

  输入用户名、邮箱地址及密码。

  运行命令:python manage.py runserver ,启动服务。

  浏览器中输入 http://127.0.0.1:8000/admin/ 并访问,可以看见管理员登录界面。

  可以在“setting”文件中设置“LANGUAGE_CODE”选择使用哪种语言。

 

  • 让poll app在管理员界面可修改

  编辑“polls/admin.py”文件:

1 from django.contrib import admin
2 
3 from .models import Question
4 
5 admin.site.register(Question)

  现在可以在管理员界面看见Questions的相关信息了,可以对其进行增删改等操作。

 

posted @ 2020-09-30 17:43  洛洛沙  阅读(112)  评论(0)    收藏  举报