灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
当我开始的时候,我不知道有一个Paginator,确保你知道它的存在!!
其他回答
为具有相同结构的遗留表集创建动态模型:
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()
这假设您拥有具有相同结构的遗留表。您不需要创建一个模型来包装每个表,而是定义一个基本模型,并动态构造与特定表交互所需的类。
使用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'
它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。
(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)
PyCharm和Wingware IDE是很好的工具,如果你有钱支付许可证。
因为我是一个很差的开发人员,所以我在Eclipse中使用PyDev。
因为Django的“视图”只需要是返回HttpResponse的可调用对象,你可以很容易地创建基于类的视图,就像Ruby on Rails和其他框架中的那样。
有几种方法可以创建基于类的视图,下面是我最喜欢的:
from django import http
class RestView(object):
methods = ('GET', 'HEAD')
@classmethod
def dispatch(cls, request, *args, **kwargs):
resource = cls()
if request.method.lower() not in (method.lower() for method in resource.methods):
return http.HttpResponseNotAllowed(resource.methods)
try:
method = getattr(resource, request.method.lower())
except AttributeError:
raise Exception("View method `%s` does not exist." % request.method.lower())
if not callable(method):
raise Exception("View method `%s` is not callable." % request.method.lower())
return method(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return http.HttpResponse()
def head(self, request, *args, **kwargs):
response = self.get(request, *args, **kwargs)
response.content = ''
return response
您可以在基本视图中添加各种其他东西,如条件请求处理和授权。
一旦你设置好了你的视图,你的urls.py将看起来像这样:
from django.conf.urls.defaults import *
from views import MyRestView
urlpatterns = patterns('',
(r'^restview/', MyRestView.dispatch),
)
在urlconf中使用reverse。
这是我不明白为什么它不是默认的那些技巧之一。
这里有一个链接到我拿起它的地方: http://andr.in/2009/11/21/calling-reverse-in-django/
下面是代码片段:
从django.conf.urls.defaults导入* 从django.core.urlresolvers导入反向 从django.utils.functional导入lazy django。http导入HttpResponse Reverse_lazy = lazy(reverse, str) Urlpatterns = patterns(", url(r'^comehere/', lambda request: HttpResponse('Welcome!'), name='comehere'), url (r“^ $”,“django.views.generic.simple.redirect_to”, {'url': reverse_lazy('comehere')}, name='root') )