Django实践,最佳?

官方文档:

https://docs.djangoproject.com/en/1.8/intro/overview/

学习过程中遇到的一些问题:

1.使用模板返回HttpResponse的两种形式:
1.1

template = loader.get_template('index.html')
context = RequestContext(request,{
    'movies' :movies
})
return HttpResponse(template.render(context))

1.2

context={'movies':movies}
#return render(request,'index.html',context)

2.返回JsonResponse序列化的问题

model to dict 的解决方法

movies = Movie.objects.values('title','siteScore')
return JsonResponse(dict(data=list(movies)))

{

    data:[

        {

        siteScore: 8.8,
        title: “大圣归来”

}

]

}

3.关于models查询

3.1
group by的使用:

Movie.objects.values('year').annotate(count=Count('year'))

相当于 sql: SELECT year,count(*) from datatalk_movie group by year

3.2
like的使用

movies = Movie.objects.filter(title__contains=query).values('title','siteScore')

关于query,官方文档:https://docs.djangoproject.com/en/1.8/topics/db/queries/

4.url 参数获取与匹配

If your url is something like domain/search/?q=haha, Then you would use request.GET.get('q', '').
q is the parameter you want, And ” is the default value if q isn’t found.
If you are instead just configuring your URLconf, Then your captures from the regex are passed to the function as arguments (or named arguments).
Such as:

(r’^user/(?P\w{0,50})/$’, views.profile_page,),
Then in your views.py you would have

def profile_page(request, username):
# Rest of the method

详细 django文档:https://docs.djangoproject.com/en/1.8/topics/http/urls/

5.解决了上述问题之后,问题来了,project 和 app 之间该如何进行组织,模块哪些能复用哪些不能。
详见 django 最佳实践:
https://lincolnloop.com/django-best-practices/
中文版:
https://github.com/yangyubo/zh-django-best-practices/blob/master/readme.rst

DjangoCon 2008: Reusable Apps

https://www.youtube.com/watch?v=A-S0tqpPga4

6.现在终于可以开开心心写代码了,但问题又来了,如果都把query硬写在views.py里,万一逻辑复杂了就不好办了,修改数据库字段了还得每个地方去修改下,这时就可以用Manager 或 QuerySet 来编写自己的orm操作,可以看这篇文章了解下。

http://www.dabapps.com/blog/higher-level-query-api-django-orm/

译文:http://www.oschina.net/translate/higher-level-query-api-django-orm

Django实践,最佳?》上有1条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注