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

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


当前回答

为具有相同结构的遗留表集创建动态模型:

class BaseStructure(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)

    class Meta:
        abstract=True

class DynamicTable(models.Model):
    table_name = models.CharField(max_length=20)

    def get_model(self):
        class Meta:
            managed=False
            table_name=self.table_name

        attrs = {}
        attrs['Meta'] = Meta

        # type(new_class_name, (base,classes), {extra: attributes})
        dynamic_class = type(self.table_name, (BaseStructure,), attrs) 
        return dynamic_class

customers = DynamicTable.objects.get(table_name='Customers').get_model()
me = customers.objects.get(name='Josh Smeaton')
me.address = 'Over the rainbow'
me.save()

这假设您拥有具有相同结构的遗留表。您不需要创建一个模型来包装每个表,而是定义一个基本模型,并动态构造与特定表交互所需的类。

其他回答

这增加了上面关于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>

使用数据库迁移。使用南。

使用IPython可以在任何级别跳转到代码中,并使用IPython的功能进行调试。一旦你安装了IPython,就把这段代码放在你想调试的地方:

from IPython.Shell import IPShellEmbed; IPShellEmbed()()

然后,刷新页面,转到runserver窗口,您将进入一个交互式IPython窗口。

我有一个片段设置在TextMate,所以我只是键入ipshell和点击标签。没有它我活不下去。

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

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