首页 > 其他 > 详细

django官方demo翻译简化版 二

时间:2020-05-11 21:03:15      阅读:119      评论:0      收藏:0      [点我收藏+]

数据库引擎的设置

打开mysite/settings.py配置文件,默认配置的数据库是SQLite.如果需要修改使用别的数据库,那么修改配置文件里的DATABASES ‘default‘,里面有如下几个选项:

  ENGINE-可以选择‘django.db.backends.sqlite3‘‘django.db.backends.postgresql‘‘django.db.backends.mysql‘, or ‘django.db.backends.oracle‘或者别的数据库

  NAME-数据库的名称。如果你使用SQLite,数据库将会是你电脑上的某个文件。换句话说,NAME应该是一个完整的文件的名称及绝对路径的组合。默认的值os.path.join(BASE_DIR, ‘db.sqlite3‘)是会生成在你的项目目录下的

假如你使用的是别的数据库,那么别的选项例如 USERPASSWORD, 以及 HOST一定要有。

可以在配置文件mysite/settings.py里通过TIME_ZONE配置项来配置自己应用的时区

注意一下配置文件的INSTALLED_APPS配置项,里面是如今所有已经集成在应用里的模块。

默认情况下,INSTALLED_APPS包括下面的模块:

  django.contrib.admin -django内置的管理后台

  django.contrib.auth-django的认证系统

  django.contrib.contenttypes-各种内容框架

  django.contrib.sessions -django的sessions模块

  django.contrib.messages-django的消息框架

  django.contrib.staticfiles -django的管理静态文件的模块

数据库表的创建

python manage.py migrate

建立数据库模型

在poll项目中我们创建2个模型:Question及Choice。一个Question包括一个问题及发布的时间。一个Choice有2个属性:选项及总票数。每个Choice是和Question绑定在一起的

上述这些文字描述都可以在Python类中表达出来,如下polls/models.py:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(‘date published‘)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)  
每个模型都是继承自类django.db.models.Model.每个模型又包括了很多属性值也就是数据库中的字段每个field都代表了一个Field类的一个实例,比如CharField代表character,DateTimeField代表日期。这些用来区分字段的类型一些field可以设置一些属性值,比如CharField可以设置max_length,我们设置votes这个属性的defalut值为0最后我们注意定义一个2者之间的联系,使用ForeignKey,这个告诉django,每个Choice被绑定到一个Question上。django支持多种一般数据库的关系:多对一,多对多,一对多激活
模型激活
首先我们应该告诉django,我们polls这个应用被引入到diango中
在mysite/settings.py文件中加入如下一行‘polls.apps.PollsConfig‘,然后代码会显示成如下:
INSTALLED_APPS = [
    polls.apps.PollsConfig,
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
]

然后运行如下命令,告知django,我们的数据库有了新的变动:

python manage.py makemigrations polls

生成数据库表,运行如下命令:

python manage.py migrate

通过如上学习,可以知道在数据库中生成表结构可以按照如下步骤:

  在models.py中新建自己的数据模型

  运行python manage.py makemigrations 来告知django数据模型变动

  运行 python manage.py migrate去在数据库生成表结构

通过django自带的数据库API来调试

通过如下命令进入调试模式:

python manage.py shell

按照如下进行尝试:

>>> 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
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模型及Choice的代码,修改polls/models.py,新增如下:

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

我们给model新建一个自定义的方法,polls/models.py:

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

然后我们重新运行python manage.py shell :

>>> from polls.models import Choice, Question

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

# Django provides a rich database lookup API that‘s entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: Whats up?>]>
>>> Question.objects.filter(question_text__startswith=What)
<QuerySet [<Question: Whats 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: Whats 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: Whats 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: Whats 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()

使用Django Admin

创建一个管理用户

在项目下运行如下命令:

 python manage.py createsuperuser

然后输入用户名,email及密码,然后使用如下命令启动项目:

python manage.py runserver

我们等待启动后,在浏览器中访问http://127.0.0.1:8000/admin/,输入刚才的用户及密码登录

然后把我们自己新建的模型注册到django的管理后台中,使用如下命令,在polls/admin.py:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

然后我们可以自由操作后管,自行做一些练习

django官方demo翻译简化版 二

原文:https://www.cnblogs.com/doumayi/p/12871274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!