灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
使用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'
它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。
(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)
其他回答
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))
在生产环境中自动设置'DEBUG'属性(settings.py)
import socket
if socket.gethostname() == 'productionserver.com':
DEBUG = False
else:
DEBUG = True
由:http://nicksergeant.com/2008/automatically-setting-debug-in-your-django-app-based-on-server-hostname/
不要硬编码你的url !
使用url名称,使用反向函数来获取url本身。
在定义URL映射时,为URL指定名称。
urlpatterns += ('project.application.views'
url( r'^something/$', 'view_function', name="url-name" ),
....
)
确保每个URL的名称是唯一的。
我通常有一个一致的格式“项目-应用程序-视图”,例如:“cbx-forum-thread”用于线程视图。
更新(无耻地窃取ayaz的添加):
这个名称可以在带有url标记的模板中使用。
Django调试工具栏真的很棒。它实际上并不是一个工具栏,而是一个侧栏,告诉您是什么带来了您正在查看的页面的各种信息——DB查询、发送到模板的上下文变量、信号等等。
与Django一起使用Jinja2。
如果你发现Django模板语言有极大的限制(就像我一样!),那么你不必被它所困。Django很灵活,模板语言与系统的其余部分是松散耦合的,所以只需插入另一种模板语言,并使用它来呈现http响应!
我使用的是Jinja2,它几乎就像一个增强版的django模板语言,它使用相同的语法,并允许你在if语句中使用表达式!不再制作自定义if标记,如if_item_in_list!你可以简单地说%{if item in list %},或者{% if object。字段< 10%}。
但这还不是全部;它有更多的功能来简化模板创建,我不能在这里一一介绍。