灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的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
其他回答
使用isapi-wsgi和Django -pyodbc在Windows上使用IIS和SQL Server运行Django !
当将变量从视图传递到模板时,输入响应字典会变得很乏味。我发现使用locals()一次性传递所有局部变量很好。
def show_thing(request, thing_id):
thing = Thing.objects.get(pk=thing_id)
return render_to_response('templates/things/show.html', locals())
(本质上不是一个隐藏的特性,但对于刚接触Python和Django的人来说还是很有帮助的。)
编辑:显然,显式比隐式更好,但这种方法在开发过程中是有帮助的。
这增加了上面关于Django URL名称和反向URL调度的回复。
URL名称也可以在模板中有效地使用。例如,对于一个给定的URL模式:
url(r'(?P<project_id>\d+)/team/$', 'project_team', name='project_team')
你可以在模板中有以下内容:
<a href="{% url project_team project.id %}">Team</a>
dir()和提高评估误差()
为了在开发过程中调试/探索事物的状态,我使用了以下技巧:
...
to_see = dir(inspect_this_thing)
to_see2 = inspect_this_thing.some_attribute
raise ValueError("Debugging")
...
当你处理django中没有很好文档的部分时,这是特别有用的。changed_fields是我最近使用的一个)。
当地人()。
使用python内置的locals()命令为你创建一个字典,而不是为模板上下文写出每个变量:
#This is tedious and not very DRY
return render_to_response('template.html', {"var1": var1, "var2":var2}, context_instance=RequestContext(request))
#95% of the time this works perfectly
return render_to_response('template.html', locals(), context_instance=RequestContext(request))
#The other 4.99%
render_dict = locals()
render_dict['also_needs'] = "this value"
return render_to_response('template.html', render_dict, context_instance=RequestContext(request))
在自定义视图装饰器中使用wraps装饰器来保留视图的名称、模块和文档字符串。如。
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
def view_decorator(fun):
@wraps(fun)
def wrapper():
# here goes your decorator's code
return wrapper
注意:如果作者没有定义__name__属性,则在基于类的视图(具有__call__方法定义的视图)上无效。作为一种变通方法:
from django.utils.decorators import available_attrs
...
@wraps(fun, assigned=available_attrs(fun))