Opened 17 years ago

Closed 17 years ago

#6512 closed (wontfix)

Complete model_api documentation in order to include an example of ORM generation with custom SQL

Reported by: Manuel Saelices Owned by: nobody
Component: Documentation Version: dev
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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.

Change History (1)

comment:1 by James Bennett, 17 years ago

Resolution: wontfix
Status: newclosed

I'm inclined to punt on this, just because it's starting to blur the line of how much Django should document Python features -- it's not a big conceptual leap from "I have this data in the right format for an object of type X" to "I can pass it to the constructor for X".

Note: See TracTickets for help on using tickets.
Back to Top