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代表着一个资源.当然我 ...
随机推荐
- 数据结构(二) --- 伸展树(Splay Tree)
文章图片和代码来自邓俊辉老师课件 概述 伸展树(Splay Tree),也叫分裂树,是一种二叉排序树,它能在O(log n)内完成插入.查找和删除操作.它由丹尼尔·斯立特Daniel Sleator ...
- 三:Mybatis知识整理(3)
一:mybatis中模糊查询的方法: 1.直接传参法:在java传参时进行拼接 -- %keyword% 2.mysql内置函数:concart('%',#{keyword},'%') -- 拼接sq ...
- 基于easyUI实现权限管理系统(三)——角色管理
此文章是基于 EasyUI+Knockout实现经典表单的查看.编辑 一. 相关文件介绍 1. role.jsp:角色管理界面 <!DOCTYPE html PUBLIC "-//W3 ...
- PHP+Xdebug实现远程调试
以前以为php调试时服务器端和IDE必须在同一台机子上,无意发现xdebug其实是支持远程调试的. 尝试之后发现可以配置成功,还是可以调试代码的感觉爽啊! php所在Ubuntu服务器 ...
- JavaScript中按键事件的e.keyCode || e.which || e.charCode
1.浏览器的按键事件 浏览器有3种按键事件——keydown,keypress和keyup,分别对应onkeydown.onkeypress和onkeyup3个事件句柄. 一个典型的按键会产生所有这三 ...
- Angular1组件通讯方式总结
这里需要将Angular1分为Angular1.5之前和Angular1.5两个不同的阶段来讲,两者虽然同属Angular1,但是在开发模式上还是有较大区别的.在Angular1.4及以前,主要是基于 ...
- iOS线程和进程的区别和联系
线程和进程的区别主要在于它们是不同的操作系统资源管理方式.进程有独立的地址空间,一个进程崩溃后,在保护模式的影响下不会对其他进程产生影响,而线程只是一个进程中的不同执行路径.线程有自己的堆栈和局部变量 ...
- 基础架构之Maven私有库
Maven对于Java开发来说肯定不会陌生,由于各种问题,公司常常需要搭建自己的私有Maven仓库. (一) 环境要求 Centos 7.5.1804 Docker 18.06.1-ce sonat ...
- element ui下拉框如何实现默认选择?
<template> <el-select v-model="value4" clearable placeholder="请选择"> ...
- 落地生根两周年,微软Azure进入2.0时代
By: 申元庆 微软亚太科技有限公司董事长 微软亚太研发集团首席运营官 微软中国云计算与企业总经理 仿佛就在转眼间,微软Azure已经在中国落地生根两年了. 长风破浪会有时,直挂云帆济沧海.微软云技术 ...