Django新手指南(2)

编写你的第一个Django程序,第一部分(下)

启用模型

 

刚才的一小段有关模型的代码,能够让Django做很多事情。有了这些代码,Django能够:

l         为程序创建对应的数据表。

l         PollChoice对象创建数据库访问API

 

哲理

Django程序是“插入式的”:你可以在多个项目中使用一个程序,你还可以将程序打包分发,因为这些程序不需要被绑定到Django的安装环境中。

 

再次编辑settings.py文件,为INSTALLED_APPS加入“mysite.polls”。就像下面所显示的一样:

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'mysite.polls'

)

 

现在Django就知道mysite项目中包含了polls程序了。现在我们执行另一条命令:

python manage.py sql polls

 

你应该能够看到类似于下面的输出(polls程序的创建数据表SQL):

BEGIN;

CREATE TABLE "polls_poll" (

    "id" serial NOT NULL PRIMARY KEY,

    "question" varchar(200) NOT NULL,

    "pub_date" timestamp with time zone NOT NULL

);

CREATE TABLE "polls_choice" (

    "id" serial NOT NULL PRIMARY KEY,

    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),

    "choice" varchar(200) NOT NULL,

    "votes" integer NOT NULL

);

COMMIT;

 

注意以下几点:

l         真实的输出会根据你所使用的数据库有所不同。

l         数据表的名字由程序的名字(polls)和模型的小写名字(pollchoice)组成(你可以重写这个行为)。

l         主键(ID)是自动添加的(这个你也可以重写)。

l         根据命名规范,Django会给外键字段加上“_id”,你还是可以重写这个行为。

l         外键关系由REFERENCES语句显式声明。

l         生成的语句对你所用的数据库都是自适应的,所以类似于auto_incrementMySQL)、serialPostgreSQL)或integer primary keySQLite)的数据库字段都会自动进行处理。在引用字段名称的时候也是自适应的——会使用双引号或单引号。本文的作者使用的是PostgreSQL数据库,所以例子中输出的是PostgreSQL语法。

l         输出的SQL语句并不会在数据库内执行——它只是打印出来让你了解Django认为什么样的SQL是必须的。如果你要执行,之需要复制粘贴到数据库命令行下就可以了。但是,我们等会就能看到,Django有更简单的方法来执行SQL

 

如果你有兴趣,也可以执行以下命令:

l         python manage.py validate 检测在生成模型的时候是否有错误。

l         python manage.py sqlcustom polls 输出程序中定义的custom SQL语句(比如表或约束的修改)。

l         python manage.py sqlclear polls 根据有哪些表存在于数据库中,输出必要的DROP TABLE语句。

l         python manage.py sqlindexes polls 输出CREATE INDEX语句。

l         python manage.py sqlall polls 组合输出sqlsqlcustomsqlindexes的结果。

 

这些命令的输出结果能够帮助你理解在程序底层到底做了什么处理。

 

现在,再次执行syncdb命令来创建模型对应的数据表:

python manage.py syncdb

 

syncdb命令会给INSTALLED_APPS中在数据库里没有对应数据表的程序执行sqlall操作。这个操作根据你上一次执行syncdb的结果,为项目中所有的程序创建对应的表、初始化数据并创建索引。syncdb你想调用多少次就能调用多少次,而它只会创建数据库里还不存在的表。

 

Read the django-admin.py documentation for full information on what the manage.py utility can do.

想了解manage.py工具更多的功能,请阅读django-admin.py的文档

 

使用模型API

 

现在,进入到Python的命令行环境中,开始使用Django提供的API吧。要进入命令行,输入下面的命令:

python manage.py shell

 

我们没有直接使用python命令进入命令行,因为manage.py会为你配置项目环境。配置环境包括以下两点:

  • sys.path中加入mysite。便捷起见,项目中所引用的模块都是以Python的“点路径”的方式来表示(比如“mysite.polls.models”)。为了正常工作,mysite包就必须在sys.path内。

我们已经看到了一个例子:INSTALLED_APPS就是一组用“点路径”方式表示的包的集合。

  • 设置DJANGO_SETTINGS_MODULE环境变量,这个变量会将settings.py的路径告诉Django

 

忽略manage.py

如果你不想用manage.py,没问题,只要确定mysitePython路径的根级别下然后给mysite.settings设置DJANGO_SETTINGS_MODULE环境变量。

要了解更多的内容,请参考django-admin.py文档。

 

进入命令行后,请浏览Django数据库API

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

 

# No polls are in the system yet.

>>> Poll.objects.all()

[]

 

# Create a new Poll.

>>> import datetime

>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())

 

# Save the object into the database. You have to call save() explicitly.

>>> p.save()

 

# Now it has an ID. Note that this might say "1L" instead of "1", depending

# on which database you're using. That's no biggie; it just means your

# database backend prefers to return integers as Python long integer

# objects.

>>> p.id

1

 

# Access database columns via Python attributes.

>>> p.question

"What's up?"

>>> p.pub_date

datetime.datetime(2007, 7, 15, 12, 00, 53)

 

# Change values by changing the attributes, then calling save().

>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)

>>> p.save()

 

# objects.all() displays all the polls in the database.

>>> Poll.objects.all()

[<Poll: Poll object>]

 

慢着,<Poll: Poll object>这样的形式绝对不是一个直白的表达方式。我们可以修改模型的代码(在polls/models.py文件里),给PollChoice各加入一个__unicode__()方法来解决这个问题:

class Poll(models.Model):

    # ...

    def __unicode__(self):

        return self.question

 

class Choice(models.Model):

    # ...

    def __unicode__(self):

        return self.choice

 

如果__unicode__()看起来好像没用

如果在模型中加入了__unicode__()方法,但是在命令行里对象的表现方式又没有任何改变,那你可能就是在用旧版本的Django。(当前的新手入门是建立在最新的Django版本上的)如果你是从SVN中获取的Django开发版本(详细信息看这里),你就不会有这些问题。

如果你坚持要用Django的旧版本,那你就该参考Django 0.96的新手入门,这篇文章中会包含一些只在Django最新开发版本中包含的特性。

 

给模型加上__unicode__()方法是很重要的,不光是为了在命令行里能够让你保持思路清晰,而且在Django自动生成的管理界面里对象表现也是会被用到的。

 

为什么是__unicode__()而不是django.db.model.Model.__str__()

如果你熟悉Python,你可能会有在模型类里使用django.db.model.Model.__str__()方法的习惯而不会去使用__unicode__()。我们用__unicode__()方式是因为Django模型默认处理Unicode数据。当数据库里的数据返回时,它们全都会被转成Unicode编码。

Django模型有个默认的django.db.model.Model.__str__()方法来调用__unicode__()方法并将结果转换成UTF8格式。这意味着unicode(p)会返回Unicode字符串,而str(p)会返回一个UTF8编码的普通字符串

如果这些东西让你很困扰,那就只需要记住给模型类加入__unicode__()方法。幸运的话,这些代码会正常工作。

 

上面提到的都是Python的魔术方法。现在我们加上一个自定义方法做演示:

import datetime

# ...

class Poll(models.Model):

    # ...

    def was_published_today(self):

        return self.pub_date.date() == datetime.date.today()

 

请注意增加了import datetime部分是为了引用Python的标准日期时间模块。

 

我们再次运行python manage.py shell回到命令行下:

>>> from mysite.polls.models import Poll, Choice

 

# Make sure our __unicode__() addition worked.

>>> Poll.objects.all()

[<Poll: What's up?>]

 

# Django provides a rich database lookup API that's entirely driven by

# keyword arguments.

>>> Poll.objects.filter(id=1)

[<Poll: What's up?>]

>>> Poll.objects.filter(question__startswith='What')

[<Poll: What's up?>]

 

# Get the poll whose year is 2007. Of course, if you're going through this

# tutorial in another year, change as appropriate.

>>> Poll.objects.get(pub_date__year=2007)

<Poll: What's up?>

 

>>> Poll.objects.get(id=2)

Traceback (most recent call last):

    ...

DoesNotExist: Poll 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 Poll.objects.get(id=1).

>>> Poll.objects.get(pk=1)

<Poll: What's up?>

 

# Make sure our custom method worked.

>>> p = Poll.objects.get(pk=1)

>>> p.was_published_today()

False

 

# Give the Poll 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.

>>> p = Poll.objects.get(pk=1)

>>> p.choice_set.create(choice='Not much', votes=0)

<Choice: Not much>

>>> p.choice_set.create(choice='The sky', votes=0)

<Choice: The sky>

>>> c = p.choice_set.create(choice='Just hacking again', votes=0)

 

# Choice objects have API access to their related Poll objects.

>>> c.poll

<Poll: What's up?>

 

# And vice versa: Poll objects get access to Choice objects.

>>> p.choice_set.all()

[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

>>> p.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 poll whose pub_date is in 2007.

>>> Choice.objects.filter(poll__pub_date__year=2007)

[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

 

# Let's delete one of the choices. Use delete() for that.

>>> c = p.choice_set.filter(choice__startswith='Just hacking')

>>> c.delete()

 

要了解更多的数据库API只是,请查阅Database API reference

 

当你对API有所了解之后,可以开始第二部分来学习Django自动生成后台是怎样工作的。

 

 

期末大作业基于python的足球运动员数据分析源码+数据集(高分项目),个人经导师指导并认可通过的高分设计项目,评审分98分,项目中的源码都是经过本地编译过可运行的,都经过严格调试,确保可以运行!主要针对计算机相关专业的正在做大作业、毕业设计的学生和需要项目实战练习的学习者,资源项目的难度比较适中,内容都是经过助教老师审定过的能够满足学习、使用需求,如果有需要的话可以放心下载使用。 期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于python的足球运动员数据分析源码+数据集(高分项目)期末大作业基于pyth
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值