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

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


当前回答

如果你还没读过《Unbreaking 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'

它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。

(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)

当你开始设计你的网站时,网页设计应用程序是非常有用的。一旦导入,你可以添加它来生成示例文本:

{% load webdesign %}
{% lorem 5 p %}

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))

如果你还没读过《Unbreaking Django》。它包含了很多关于django陷阱的有用信息。

使用信号动态地添加访问方法。

我在django photologue中看到过这种技术:对于添加的任何Size对象,post_init信号都会将相应的方法添加到Image模型中。 如果您添加了一个巨型站点,检索巨型分辨率图片的方法将是image.get_giant_url()。

这些方法是通过调用post_init信号中的add_accessor_methods来生成的:

def add_accessor_methods(self, *args, **kwargs):
    for size in PhotoSizeCache().sizes.keys():
        setattr(self, 'get_%s_size' % size,
                curry(self._get_SIZE_size, size=size))
        setattr(self, 'get_%s_photosize' % size,
                curry(self._get_SIZE_photosize, size=size))
        setattr(self, 'get_%s_url' % size,
                curry(self._get_SIZE_url, size=size))
        setattr(self, 'get_%s_filename' % size,
                curry(self._get_SIZE_filename, size=size))

参见photologue的源代码。用于实际使用的模型。