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代表着一个资源.当然我 ...
随机推荐
- jQuery 的动画效果图片----隐藏打开方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- golang学习之mgo操作mongodb
mgo是mongodb的golang驱动,测试代码: // mgotest project main.go package main import ( "fmt" "ti ...
- Thread 的join方法
package com.cn.test.thread; public class TestJoin extends Thread{ private String name; public TestJo ...
- spring实现固定时间定时器
此文章是基于 搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台 一. jar包介绍 1. spring-framework-4.3.4.RELEASE 的 lib ...
- 用KMP算法与Trie字典树实现屏蔽敏感词(UTF-8编码)
前几天写好了字典,又刚好重温了KMP算法,恰逢遇到朋友吐槽最近被和谐的词越来越多了,于是突发奇想,想要自己实现一下敏感词屏蔽. 基本敏感词的屏蔽说起来很简单,只要把字符串中的敏感词替换成“***”就可 ...
- oracle中,改变表名和字段名的大小写
1.将表名和字段名改为大写 见--http://www.cnblogs.com/wenboge/articles/4121331.html 2.将表名和字段名改为小写 ①改表名为小写 begin f ...
- javascript获取元素样式值
使用css控制页面有4种方式,分别为行内样式(内联样式).内嵌式.链接式.导入式. 行内样式(内联样式)即写在html标签中的style属性中,如<div style="width:1 ...
- create-react-app找不到配置项
npm run eject 这个一个不可逆过程,一旦你执行了,就不能回到初始化
- Sort函数的用法
快速排序sort的用法:(适用于int float double char ...) 记得加头文件! 记得加头文件! 记得加头文件! 头文件: #include <algorithm> ...
- C/C++ OpenCV读取视频与调用摄像头
原文:http://blog.csdn.net/qq78442761/article/details/54173104 OpenCV通过VideoCapture类,来对视频进行读取,调用摄像头 读取视 ...