灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。

请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。


当前回答

Virtualenv + Python =救生圈,如果你在多个Django项目中工作,而且它们可能都不依赖于同一个版本的Django/应用程序。

其他回答

我喜欢使用Python调试器pdb来调试Django项目。

这是一个学习如何使用它的有用链接:http://www.ferg.org/papers/debugging_in_python.html

每个人都知道有一个可以使用“manage.py runserver”运行的开发服务器,但是你知道还有一个用于提供静态文件(CSS / JS / IMG)的开发视图吗?

新手总是感到困惑,因为Django没有提供任何提供静态文件的方法。这是因为开发团队认为这是实际Web服务器的工作。

但是在开发时,你可能不想设置Apache + mod_wisi,它很重。然后你只需要在urls.py中添加以下内容:

(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/path/to/media'}),

您的CSS / JS / IMG将在www.yoursite.com/site_media/上提供。

当然,不要在生产环境中使用它。

在Django 1.2+中使用.exists(),在以前的版本中使用.count(),而不是计算整个queryset来检查是否返回任何结果。

exists()和count()都清除order by子句,并从DB中检索单个整数。然而exists()将总是返回1,而as count可能会返回更高的值,对这些值将手动应用限制。exists()中使用的has_result和count()中使用的get_count的源代码。

因为它们都返回一个整数,所以没有模型实例化,在内存中加载模型属性,也没有大的TextFields在你的DB和应用程序之间传递。

如果你已经计算了查询,.count()计算len(cached_result), .exists()计算bool(cached_result)

效率不高—例1

books = Books.objects.filter(author__last_name='Brown')
if books:
    # Do something

效率不高——例2

books = Books.objects.filter(author__last_name='Brown')
if len(books):
    # Do something

高效-例1

books = Books.objects.filter(author__last_name='Brown')
if books.count():
    # Do something

高效-例2

books = Books.objects.filter(author__last_name='Brown')
if books.exists():
    # Do something

因为Django的“视图”只需要是返回HttpResponse的可调用对象,你可以很容易地创建基于类的视图,就像Ruby on Rails和其他框架中的那样。

有几种方法可以创建基于类的视图,下面是我最喜欢的:

from django import http

class RestView(object):
    methods = ('GET', 'HEAD')

    @classmethod
    def dispatch(cls, request, *args, **kwargs):
        resource = cls()
        if request.method.lower() not in (method.lower() for method in resource.methods):
            return http.HttpResponseNotAllowed(resource.methods)
        try:
            method = getattr(resource, request.method.lower())
        except AttributeError:
            raise Exception("View method `%s` does not exist." % request.method.lower())
        if not callable(method):
            raise Exception("View method `%s` is not callable." % request.method.lower())
        return method(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return http.HttpResponse()

    def head(self, request, *args, **kwargs):
        response = self.get(request, *args, **kwargs)
        response.content = ''
        return response

您可以在基本视图中添加各种其他东西,如条件请求处理和授权。

一旦你设置好了你的视图,你的urls.py将看起来像这样:

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

urlpatterns = patterns('',
    (r'^restview/', MyRestView.dispatch),
)

我从sorl-thumbnails应用程序的文档中学到了这一点。你可以在模板标签中使用“as”关键字来在模板的其他地方使用调用的结果。

例如:

{% url image-processor uid as img_src %}
<img src="{% thumbnail img_src 100x100 %}"/>

这一点在Django templatetag文档中提到过,但仅用于引用循环。他们并没有说你也可以在其他地方使用它(任何地方?)