Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are using PostgreSQL as a database backend and don't need cross database compatibility, you can use the <a href="http://www.postgresql.org/docs/9.1/static/functions-window.html" rel="nofollow">powerful window functions</a> that allow something like that :</p> <p>Imagine your table looks like that :</p> <pre><code>CREATE TABLE x ( i serial primary key, value integer not null, date timestamp, category text); </code></pre> <p>And you want the most recent value for each category. You will do :</p> <pre><code>SELECT first_value(i) over w, first_value(value) over w, first_value(date) over w category, FROM x WINDOW w AS (PARTITION BY category ORDER BY date DESC); </code></pre> <p>You can use such a query in django via the <code>raw</code> method on the query set manager :</p> <pre><code>ModelX.objects.raw("""SELECT DISTINCT ....... FROM x WINDOW w .....""") </code></pre> <p>To get the last N entries by category, the query is a little more complicated and involves a subquery :</p> <pre><code>SELECT i, value, date, category FROM (SELECT i, value, date, category, row_number() over w FROM x WINDOW w AS (PARTITION BY category ORDER BY date DESC)) AS subquery WHERE subquery.row_number &lt;= 30; </code></pre> <p>Seeing that, you could even make a view :</p> <pre><code>CREATE VIEW x_with_reverse_date_index AS (SELECT i, value, date, category, row_number() over w FROM x WINDOW w AS (PARTITION BY category ORDER BY date DESC)); </code></pre> <p>And create a django model that queries this view :</p> <pre><code>class ModelX(models.Model): ... ... row_number = models.IntegerField("Row number when ordering by date desc") class Meta: db_table = 'x_with_reverse_date_index' </code></pre> <p>and query it "normally" :</p> <pre><code>ModelX.objects.filter(category__in = ('catA','catB'), row_number__lte = 30) ModelX.objects.filter(row_number = 29) ... </code></pre> <p><strong>Warning</strong> : again, don't do this if you need a code that works on another database engine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload