Get related column on .annotate() data Django

荒凉一梦 提交于 2019-12-01 07:28:27

问题


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

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,

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,

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

Thanks,


回答1:


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})


来源:https://stackoverflow.com/questions/37908049/get-related-column-on-annotate-data-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!