Django 玩转API
现在,让我们进入Python的交互式shell,玩转这些Django提供给你的API。 使用如下命令来调用Python shell:
$ python manage.py shell
我们使用上述命令而不是简单地键入“python”进入python环境,是因为manage.py 设置了DJANGO_SETTINGS_MODULE 环境变量,该变环境变量告诉Django导入mysite/settings.py文件的路径。
绕开 manage.py
如果你不想使用manage.py,也没问题。只要设置DJANGO_SETTINGS_MODULE 环境变量为 mysite.settings,启动一个普通的Python shell,然后建立Django:
>>> import django
>>> django.setup()
如果以上命令引发了一个AttributeError,可能是你使用了一个和本教程不匹配的Django版本。 你可能需要换一个老一点的教程或者换一个新一点的Django版本。
你必须在与manage.py相同的目录下运行python,或确保你的目录在Python 的路径中,这样import mysite才可以工作。
所有这些信息,请参见django-admin 的文档。
一旦你进入这个shell,请探索这些数据库 API:
>>> from polls.models import Question, Choice # Import the model classes we just wrote. # No questions are in the system yet.
>>> Question.objects.all()
[] # 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. 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.
>>> 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()
[<Question: Question object>]
先等一下。<Question: Question object>对于这个对象是一个完全没有意义的表示。 让我们来修复这个问题,编辑Question模型(在polls/models.py文件中)并添加一个__str__()方法给Question和Choice:
from django.db import models class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
给你的模型添加__str__()方法很重要,不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示。
__str__ 还是 __unicode__?
对于Python 3来说,这很简单,只需使用__str__()。
对于Python 2来说,你应该定义__unicode__()方法并返回unicode 值。Django 模型具有一个默认的__str__() 方法,它会调用__unicode__()并将结果转换为UTF-8 字节字符串。这意味着unicode(p)将返回一个Unicode 字符串,而str(p)将返回一个字节字符串,其字符以UTF-8编码。Python 的行为则相反:对象的__unicode__方法调用 __str__方法并将结果理解为ASCII 字节字符串。这个不同点可能会产生困惑。
如果以上这些令你费解的话,那就使用Python 3吧。
请注意这些都是普通的Python方法。 让我们演示一下如何添加一个自定义的方法:
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)
注意import datetime 和from django.utils import timezone分别引用Python 的标准datetime 模块和Djangodjango.utils.timezone中时区相关的工具。如果你不了解Python中时区的处理方法,你可以在时区支持的文档 中了解更多的知识。
保存这些改动,然后通过python manage.py shell再次打开一个新的Python 交互式shell:
>>> from polls.models import Question, Choice # Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>] # Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<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()
[] # 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()
[<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)
[<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()
更多关于模型关联的信息,请查看访问关联的对象。更多关于如何在这些API中使用双下划线来执行字段查询的信息,请查看 字段查询。更多关于数据库API的信息,请查看我们的 数据库API参考。
如果你适应了这些API,可以阅读本教程的第2部分来让Django的自动管理界面工作起来。
########################################################
1. def __str__(self): # __unicode__ on Python 2
内置函数 __str__(), __unicode__()的作用(Python 2用的是__unicode__, python 3用的是__str__):
__str__()用于表示对象代表的含义,返回一个字符串.实现了__str__()方法后,可以直接使用print语句输出对象,也可以通过函数str()触发__str__()的执行.这样就把对象和字符串关联起来,便于某些程序的实现,可以用这个字符串来表示某个类
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit:
'''Fruit类''' #为Fruit类定义了文档字符串
def __str__(self): # 定义对象的字符串表示
return self.__doc__ if __name__ == "__main__":
fruit = Fruit()
print str(fruit) # 调用内置函数str()出发__str__()方法,输出结果为:Fruit类
print fruit #直接输出对象fruit,返回__str__()方法的值,输出结果为:Fruit类
2.pub_date__year
一个属性后面跟__year过滤。
3.
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
[]
# Create choices.
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky> question和choice是一对多的关系。q是question对象,q.choice即是q对应的choice, q.choice_set调用了choice对象下内置的_set, q.choice_set.create是创建choice的方法。
Django 玩转API的更多相关文章
- 我这么玩Web Api(二):数据验证,全局数据验证与单元测试
目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试 一.模型状态 - ModelState 我理解 ...
- Django编写RESTful API(一):序列化
欢迎访问我的个人网站:www.comingnext.cn 关于RESTful API 现在,在开发的过程中,我们经常会听到前后端分离这个技术名词,顾名思义,就是前台的开发和后台的开发分离开.这个技术方 ...
- Django编写RESTful API(四):认证和权限
欢迎访问我的个人网站:www.comingnext.cn 前言: 按照前面几篇文章里那样做,使用Django编写RESTful API的基本功能已经像模像样了.我们可以通过不同的URL访问到不同的资源 ...
- python 全栈开发,Day95(RESTful API介绍,基于Django实现RESTful API,DRF 序列化)
昨日内容回顾 1. rest framework serializer(序列化)的简单使用 QuerySet([ obj, obj, obj]) --> JSON格式数据 0. 安装和导入: p ...
- Django FBV CBV以及使用django提供的API接口
FBV 和 CBV 使用哪一种方式都可以,根据自己的情况进行选择 看看FBV的代码 URL的写法: from django.conf.urls import url from api import v ...
- Django Rest Framework API指南
Django Rest Framework API指南 Django Rest Framework 所有API如下: Request 请求 Response 响应 View 视图 Generic vi ...
- Django REST Framework API Guide 01
之前按照REST Framework官方文档提供的简介写了一系列的简单的介绍博客,说白了就是翻译了一下简介,而且翻译的很烂.到真正的生产时,就会发现很鸡肋,连熟悉大概知道rest framework都 ...
- tastypie Django REST framework API [Hello JSON]
tastypie is a good thing. Haven't test it thoroughly. Gonna need some provement. Now I will introduc ...
- Django编写RESTful API(二):请求和响应
欢迎访问我的个人网站:www.comingnext.cn 前言 在上一篇文章,已经实现了访问指定URL就返回了指定的数据,这也体现了RESTful API的一个理念,每一个URL代表着一个资源.当然我 ...
随机推荐
- [Git & GitHub] 利用Git Bash进行第一次提交文件
转载:https://blog.csdn.net/dietime1943/article/details/72420042 利用Git Bash进行第一次提交文件 快下班的时候,MD群里有人问怎么向g ...
- step6: item与pipeline
目的:提取内容进行格式化输出,类似于字典 编写item文件 class JobBoleArticleItem(scrapy.Item): title = scrapy.Field() #支持传进任何数 ...
- pm2在node中的应用
pm2 是一个带有负载均衡功能的Node应用的进程管理器,当你要把你的独立代码利用全部的服务器上的所有CPU,并保证进程永远都活着,0秒的重载, pm2是完美的. 主要特性: 内建负载均衡(使用Nod ...
- HTTP中的响应协议及302、304的含义
响应协议 HTTP/1.1 200 OK:响应协议为HTTP1.1,状态码为200,表示请求成功,OK是对状态码的解释: Server: Apache-Coyote/1.1:服务器的版本信息: Con ...
- 记录开发Nodejs c++ addon的一些经验(一、技术栈)
Nodejs c++ addon 是用c++去编写Nodejs的插件 技术栈: 1.node-gyp 一个用于把c++文件编译成node可执行文件的库 2.v8 google v8引擎 用于处理c++ ...
- Postman安装及入门实践(以百度搜索为例)
一.Postman安装 可以FQ的小伙伴可以直接去官网下载:https://www.getpostman.com 如果不能,可以用我的安装包,版本找最新的:链接:https://pan.baidu.c ...
- [转]webapi部署在IIS7.5报404的解决方案
1.iis 目录权限设置 2.转自:http://www.cnblogs.com/youlies/p/6042169.html 在web.config添加如下节点 <system.webServ ...
- <Android 应用 之路> 百度地图API使用(1)
简介 详情请看百度地图官方网站 http://lbsyun.baidu.com/index.php?title=androidsdk/guide/introduction 使用方式 申请密钥,针对移动 ...
- strcmp和stricmp、strcmpi三者之间的区别(C++)
原文:http://www.cnblogs.com/tankeee/p/3957629.html #include <string.h> #include <stdio.h> ...
- Android菜单(动画菜单、360波纹菜单)
Android菜单(动画菜单.360波纹菜单) 前言:Android菜单常用集合:FragmentTabHost系统菜单.上移式菜单.360波纹菜单.展开式菜单.详解注释,可直接拿来用! 效果: ...