Search code examples
djangodjango-select-relatedrawsql

Get related column on .annotate() data Django


I created this simple set of data to illustrate my point. It is a simple model with no further relations to any other model.

enter image description here

I need to group the data above by topicid, find the max date for each group and then get the author for that date.

info = TempModel.objects
       .values('topic')
       .annotate( max=Max('date'))
       .order_by('-max')

Iterating through this in a template,

  <table>
      {% for item in info %}
      <tr>
        <td>{{ item.topicid }}</td>
        <td>{{ item.max }}</td>
        <td>{{ item.author }}</td>
      </tr>
      {% endfor %}
  </table>

produces,

enter image description here

How do I display the 'author' column for each max date?

I can do this with a raw sql query like this,

info = list(TempModel.objects
       .raw('SELECT *, max(date) AS max 
       FROM crudapp_tempmodel 
       GROUP BY topicid 
       ORDER BY date DESC'))

But I want to do it using a Django query.

The output I am looking for is,

enter image description here

If this is not possible with a Django query I would like to know.

Thanks,


Solution

  • A solution is to amalgamate another query which compares date from one query with max from the other.

    Here is the view that does this,

    def temp(request):
        info2 = TempModel.objects.all()
        info = TempModel.objects
               .values('topic')
               .annotate( max=Max('date'))
               .order_by('-max')
    
        columnlist = []
        for item in info2:
             columnlist.append([item])
    
        for item in info:
            for i in range(len(columnlist)):
                if item['max'] == columnlist[i][0].date:
                    item['author'] = columnlist[i][0].author
    
        return render(request, 'template.html', {'info': info, 'info2': info2})