灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
在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
其他回答
使用IPython可以在任何级别跳转到代码中,并使用IPython的功能进行调试。一旦你安装了IPython,就把这段代码放在你想调试的地方:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
然后,刷新页面,转到runserver窗口,您将进入一个交互式IPython窗口。
我有一个片段设置在TextMate,所以我只是键入ipshell和点击标签。没有它我活不下去。
与Django一起使用Jinja2。
如果你发现Django模板语言有极大的限制(就像我一样!),那么你不必被它所困。Django很灵活,模板语言与系统的其余部分是松散耦合的,所以只需插入另一种模板语言,并使用它来呈现http响应!
我使用的是Jinja2,它几乎就像一个增强版的django模板语言,它使用相同的语法,并允许你在if语句中使用表达式!不再制作自定义if标记,如if_item_in_list!你可以简单地说%{if item in list %},或者{% if object。字段< 10%}。
但这还不是全部;它有更多的功能来简化模板创建,我不能在这里一一介绍。
我就从我自己的一个建议开始吧:)
在settings.py中使用os.path.dirname()来避免硬编码的dirname。
如果你想在不同的位置运行你的项目,不要在你的settings.py中硬编码路径。如果你的模板和静态文件位于Django项目目录中,在settings.py中使用下面的代码:
# settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
...
STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static")
...
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
)
工作人员:我从视频《Django from the Ground Up》中得到了这个提示。
Instead of using render_to_response to bind your context to a template and render it (which is what the Django docs usually show) use the generic view direct_to_template. It does the same thing that render_to_response does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using render_to_response, but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:
<a href="{{MEDIA_URL}}images/frog.jpg">A frog</a>
这是非常有用的。事实上,+1在一般的视图上。对于简单的应用程序,Django文档大多将它们作为快捷方式显示,甚至没有views.py文件,但你也可以在自己的视图函数中使用它们:
from django.views.generic import simple
def article_detail(request, slug=None):
article = get_object_or_404(Article, slug=slug)
return simple.direct_to_template(request,
template="articles/article_detail.html",
extra_context={'article': article}
)
在我的站点模板中,我使用了一组自定义标记。寻找一种自动加载的方法(DRY,记得吗?),我发现如下:
from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')
如果你把它放在一个默认加载的模块中(例如你的主urlconf),你将有来自自定义标签模块的标签和过滤器在任何模板中可用,而不需要使用{% load custom_tag_module %}。
传递给template.add_to_builtins()的参数可以是任何模块路径;您的自定义标记模块不必存在于特定的应用程序中。例如,它也可以是项目根目录中的一个模块。“project.custom_tag_module”)。