settings.py是一个普通的python模块,其中的变量表示django设置
1.数据库配置
数据库默认使用SQLite,无需任何额外安装和操作。
如果需要使用其他数据库,就修改其中的如下部分:
ENGINE可使用:
django.db.backends.postgresql
django.db.backends.mysql
django.db.backends.oracle
NAME: 数据库名,如果是SQLite则为文件名并且是绝对路径。
另外要设置USER , PASSWORD , HOST。并确保该用户具有创建数据库的权限。
2.默认表的创建(migrate)
INSTALLED_APPS维持该django实例中所有激活的APP列表。默认就有一些APP。这些app有的至少需要一个数据表,因此在使用他们之前,我们需要在数据库中创建相应的表。
python manage.py migrate
他会根据数据库设置和INSTALLED_APPS设置进行表的创建等。
模型是数据唯一确定的来源。迁移完全来自模型(model)文件。并且django可以通过更新数据库模式来匹配当前模型。
3.创建模型model
我们创建两个模型,Question和Choice,每个Choice都关联一个Question。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),如:”date published”,如果不提供则列名会使用变量名。
有些域需要一些参数,如CharField需要max_length,这不仅用于数据库模式(scheme),也用于验证。
这里使用了数据库关系,ForeignKey表示每个Choice都关联一个Question。
仅通过这少量的代码,django就可以为该APP创建数据库模式,创建访问模型对象的数据库API。
4.安装app
django app是插件式的,我们可以在多个项目中使用,也可以发布出去。使用时我们需要告诉django:polls app被安装了。
我们需要在INSTALLED_APPS配置项中引用该APP的配置类。
‘polls.apps.PollsConfig’,
5.数据库迁移migrate
运行makemigrations告诉django模型产生了变化,并将变动存储为migration文件
python manage.py makemigrations polls
migrations是django存储模型变动的方式,他们实际上只是硬盘上的一个文件。如果需要,你可以读取和改动该文件以影响django的行为,如:polls/migrations/0001_initial.py
查看变更
python manage.py sqlmigrate polls 0001
django会做如下处理:app_table构成表名、自动添加主键ID、为外键的域名添加_id,根据数据库自动处理如自动增长等
sqlmigrate不会在数据库上运行migration(不会改变数据库)。
可以运行python manage.py check检查项目。
进行迁移操作,可以只执行此步
python manage.py migrate
6.交互shell
python manage.py shell
manage.py设置django_settings_module环境变量,他依据mysite/settings.py为django的python提供了导入路径。
如下为shell的演示操作:
>>> from polls.models import Question, Choice # 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)>]>
7.模型补充函数
为模型增加_ _str_ _方法,使得查询对象更直观而不是上述对象
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
为question模型添加如下方法作为测试
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
继续使用shell测试
>>> from polls.models import Question, Choice
# 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()
更多请参考:
模型关系:https://docs.djangoproject.com/en/2.0/ref/models/relations/
双下划线方法:https://docs.djangoproject.com/en/2.0/topics/db/queries/#field-lookups-intro
数据库API:https://docs.djangoproject.com/en/2.0/topics/db/queries/
8.admin管理页
admin是django为模型自动化生成的管理接口。
创建admin site的管理员
python manage.py createsuperuser
启动项目后访问http://localhost:8000/admin/进入登陆页面。
其中的groups , users是由django.contrib.auth提供的认证框架。
添加我们的自定义模型question , choice,需要告诉admin,question对象有一个管理员接口。编辑polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
此时可以在管理页面对该模型进行管理
从quetion模型自动生成表单,每种模型域都知道如何在admin中显示
如果显示的时间不正确,说明没有配置TIME_ZONE,典型的值为Asia/Shanghai
本文详细介绍Django框架的数据库配置及模型创建过程,包括数据库选择、表的创建与迁移、模型设计与实现,以及如何利用Django Admin进行模型管理。
316

被折叠的 条评论
为什么被折叠?



