﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
6512	Complete model_api documentation in order to include an example of ORM generation with custom SQL	Manuel Saelices	nobody	"Sometimes you have to execute custom SQL because ORM cannot get right a hard query. Ok, you can go to [http://www.djangoproject.com/documentation/model-api/#executing-custom-sql model docs] and see an example of using custom SQL.

But you'd like to using ORM and not recordsets results. It's possible to build a ORM list (ok, not a queryset) with a SQL query. 

I have read a  [http://code.djangoproject.com/browser/django/trunk/tests/modeltests/custom_methods/models.py#L23 good example] of this.

I put an example based on previous one:

{{{
#!python
class Article(models.Model):
    ...

    def custom_articles(self):
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute(""""""
        SELECT id, headline, pub_date FROM custom_methods_article
        WHERE pub_date = %s
        AND id != %s"""""", [str(self.pub_date), self.id])
        # The asterisk in ""(*row)"" tells Python to expand the list into
        # positional arguments to Article().
        return [self.__class__(*row) for row in cursor.fetchall()]
}}}

Why don't complete ''executing custom sql'' section with an example like previous one?

Before documenting this, maybe would be good be aware of [http://groups.google.com/group/django-developers/browse_frm/thread/4281b61c902ded58 this discussion], because proposal could break example code."		closed	Documentation	dev		wontfix			Unreviewed	0	0	0	0	0	0
