Python+Django笔记之二

一个简单的select * 操作的Django方式:

首先配置urls.py

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

urlpatterns = patterns(‘ ‘,
(r’^notes/$’, views.list_notes),
)

其中r’^notes/$’是regex,用于匹配url;views.list_notes是views.py中的list_notes 方法。

然后写list_notes:

def list_notes(request):
notes = Note.objects.order_by(‘-created_date’)
conduit = {
‘notes’: notes
}
return render_to_response(
‘misc/list.html’,
conduit,
context_instance = RequestContext(request),
)

其中conduit这个词来自Mass Effect 🙂

最后就是把上面的misc/list.html写出来:

{% extends “base.html” %}

{% block title %}List Notes – {{ block.super }}{% endblock %}

{% block body %}
{% if notes %}
<ul>
{% for note in notes %}
<li>{{ note.created_date }} : {{ note.message }}</li>
{% endfor %}
</ul>
{% else %}
<p>No notes yet.</p>
{% endif %}
{% endblock %}

这样用浏览器访问类似http://localhost:8000/app/notes的url时,全部notes应该就列出来了,并按时间倒序排列。

Leave a Reply

Your email address will not be published. Required fields are marked *