Code

Opened 6 years ago

Closed 6 years ago

#6512 closed (wontfix)

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

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

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.

Attachments (0)

Change History (1)

comment:1 Changed 6 years ago by ubernostrum

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

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".

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.