1、URL传参与view

urls.py views.py

from django.shortcuts import render_to_response from mysite.models import MyModel

def foobar_view(request, template_name): m_list = MyModel.objects.filter(is_new=True) return render_to_response(template_name, {'m_list': m_list}) 2、 URL /mydata/dec/31/ -- urlpatterns = patterns('', (r'^mydata/(?P<month>w{3})/(?P<day>dd)/$', views.my_view), ) -- def my_view(request, month, day): # .... 3、通用视图

urls.py views.py

from django.shortcuts import render_to_response

def object_list(request, model): obj_list = model.objects.all() template_name = 'mysite/%s_list.html' % model.name.lower() return render_to_response(template_name, {'object_list': obj_list}) 4、缺省视图参数

urls.py views.py

def page(request, num='1'): # Output the appropriate page of blog entries, according to num. # ... 5、url传参都是字符串类型 def day_archive(request, year, month, day): date = datetime.date(int(year), int(month), int(day)) 6、url传参选择post get

views.py

from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response

def method_splitter(request, GET=None, POST=None): if request.method == 'GET' and GET is not None: return GET(request) elif request.method == 'POST' and POST is not None: return POST(request) raise Http404

def some_page_get(request): assert request.method == 'GET' do_something_for_get() return render_to_response('page.html')

def some_page_post(request): assert request.method == 'POST' do_something_for_post() return HttpResponseRedirect('/someurl/')

urls.py

from django.conf.urls.defaults import * from mysite import views

urlpatterns = patterns('', # ... (r'^somepage/$', views.method_splitter, {'GET': views.some_page_get, 'POST': views.some_page_post}), # ... ) 7、自动转义:autoescape {% autoescape off %} Hello {{ name }} {% endautoescape %} 8 default默认值需要自己转义 {{ data|default:"3 < 2" }} <-- Bad! Don't do this. 9、自定义标签/自定义过滤器 10 foreignkey

b = Book.objects.get(id=50) b.publisher <Publisher: Apress Publishing> b.publisher.website u'http://www.apress.com/' p.book_set.all() p = Publisher.objects.get(name='Apress Publishing') p.book_set.filter(name__icontains='django') [<Book: The Django Book>, <Book: Pro Django>]

image.png 11 manytomanyfield class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() num_pages = models.IntegerField(blank=True, null=True)

12 django.db.models.Manager.title_count()

image.png

13 修改返回的集合:get_query_set() from django.db import models

# First, define the Manager subclass. class DahlBookManager(models.Manager): def get_query_set(self): return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')

# Then hook it into the Book model explicitly. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) # ...

//调用 Book.dahl_objects.all() Book.dahl_objects.filter(title='Matilda') Book.dahl_objects.count()

14 添加多个manager class MaleManager(models.Manager): def get_query_set(self): return super(MaleManager, self).get_query_set().filter(sex='M')

class FemaleManager(models.Manager): def get_query_set(self): return super(FemaleManager, self).get_query_set().filter(sex='F')

class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female'))) people = models.Manager() men = MaleManager() women = FemaleManager()

15 执行原始SQL:connection,models from django.db import connection, models

class PersonManager(models.Manager): def first_names(self, last_name): cursor = connection.cursor() cursor.execute(""" SELECT DISTINCT first_name FROM people_person WHERE last_name = %s""", [last_name]) return [row[0] for row in cursor.fetchone()]

class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) objects = PersonManager()