Hello,
I want to execute a semi-complex query in Django. For example I want something that is like this:
SELECT
b.*,
(SELECT count(id) FROM comments c WHERE c.blog_id = b.id) AS number_of_comments
FROM blog b
WHERE 1
From my PHP background, Code Igniter and Zend Framework has "query builders". Where you can built an SQL-query using the methods in the framework. Is this something like in Django?
What would be the best way to build and execute complex queries in Django? Is there a recommended way / best-practice to do these kinds of queries?
UPDATE:
I got it working with little changes thanks to mherren's code below. Here is the updated version of the code.
In my views.py I have this:
def index(request):
blog_posts = Blog.objects.all().annotate(Count('comment')).order_by('-pub_date')[:5]
return render_to_response('blog/index.html',
{'blog_posts': blog_posts})
In my template file (index.html) I have this:
Welcome...
{% if blog_posts %}
<ul>
{% for post in blog_posts %}
<li>
<b>
<a href="/blog/post/{{ post.id }}">{{ post.title }}</a>
</b> ({{ post.pub_date }})<br/>
{{ post.content }}<br/>
{{ post.comment__count }} comment(s)<br/>
by: {{ post.author }}<br/><br/>
</li>
{% endfor %}
</ul>
{% else %}
<p>No posts are available.</p>
{% endif %}
Hope this also helps out the others. Thanks for everything guys!