为了完成我的个人博客 notewo.com ,
这两天需要用到left join来完成一些功能,查来查去,查到了这个方法:
https://docs.djangoproject.com/en/dev/topics/db/sql/
例子如下:
先看一下SQL语句:
select a.title,a.author_id,b.blog_id,c.blog_id,count(*) as count from biziapp_blog as a left join biziapp_blogfavor as b on a.id=b.blog_id left join biziapp_comment as c on a.id=c.blog_id group by c.blog_id limit 10;
如上语句,那么写成django该如何写呢?查了文档之后发现方法如下:
- posts_list = Blog.objects.raw('select a.*,b.blog_id,count(*) as count
- from biziapp_blog as a left join biziapp_blogfavor as b on a.id=b.blog_id
- left join biziapp_comment as c on a.id=c.blog_id group by c.blog_id order
- by a.date')
这样就可以了。不过你要注意一下文档中的这段话:
There is only one field that you can't leave out - the primary key field. Django uses the primary key to identify model instances, so it must always be included in a raw query. An InvalidQuery exception will be raised if you forget to include the primary key.
如果在rawqueryset中没有包含主键的话,会报如下的错:
Raw query must include the primary key
就是说,至少要有 select a.id(主键) 这样的东西,我用了*,所以自然包含了。注意这点就行了。
效率什么的,先不说了。为了早日完成网站,自顾不暇。
另外还有一个注意的地方:结合分页和rawqueryset,这个时候会出现一个问题:
object of type 'int' has no len()
所以解决方法如下:
- paginator = Paginator(list(posts_list),8)
这样子就完美解决。
睡觉了。(=^_^=)