Complete model_api documentation in order to include an example of ORM generation with custom SQL
|Reported by:||msaelices||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Sometimes you have to execute custom SQL because ORM cannot get right a hard query. Ok, you can go to 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 good example of this.
I put an example based on previous one:
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 this discussion, because proposal could break example code.