灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
在自定义视图装饰器中使用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))
其他回答
使用xml_models创建使用XML REST API后端(而不是SQL后端)的Django模型。这是非常有用的,特别是在对第三方api建模时——你会得到你习惯的所有相同的QuerySet语法。您可以从PyPI安装它。
来自API的XML:
<profile id=4>
<email>joe@example.com</email>
<first_name>Joe</first_name>
<last_name>Example</last_name>
<date_of_birth>1975-05-15</date_of_birth>
</profile>
现在在python中:
class Profile(xml_models.Model):
user_id = xml_models.IntField(xpath='/profile/@id')
email = xml_models.CharField(xpath='/profile/email')
first = xml_models.CharField(xpath='/profile/first_name')
last = xml_models.CharField(xpath='/profile/last_name')
birthday = xml_models.DateField(xpath='/profile/date_of_birth')
finders = {
(user_id,): settings.API_URL +'/api/v1/profile/userid/%s',
(email,): settings.API_URL +'/api/v1/profile/email/%s',
}
profile = Profile.objects.get(user_id=4)
print profile.email
# would print 'joe@example.com'
它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。
(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)
不要编写自己的登录页面。如果你使用django.contrib.auth。
真正的,肮脏的秘密是,如果你也在使用django.contrib。Admin和django.template.loaders.app_directories。Load_template_source在你的模板加载器中,你也可以免费获得你的模板!
# somewhere in urls.py
urlpatterns += patterns('django.contrib.auth',
(r'^accounts/login/$','views.login', {'template_name': 'admin/login.html'}),
(r'^accounts/logout/$','views.logout'),
)
使用异步任务。使用芹菜
在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_extensions附带的。/manage.py runserver_plus工具真的很棒。
它创建了一个增强的调试页面,其中使用Werkzeug调试器为堆栈中的每个点创建交互式调试控制台(见截图)。它还提供了一个非常有用、方便的调试方法dump(),用于显示关于对象/帧的信息。
要安装,您可以使用pip:
pip install django_extensions
pip install Werkzeug
然后在settings.py中的INSTALLED_APPS元组中添加'django_extensions',并使用新的扩展启动开发服务器:
./manage.py runserver_plus
这将改变调试的方式。