Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Updated answer based on need for passing in <code>user</code> object.</p> <p>The easiest way is to deal with this in your view, but it has its problems.</p> <pre><code>for widget in widget_list: widget.latest_finished_widget = widget.finished_widget_set.filter(user=request.user).latest('created') {% for widget in widget_list %} &lt;p&gt;{{ widget.name }}&lt;/p&gt; &lt;p&gt;{{ widget.latest_finished_widget }}&lt;/p&gt; {% endfor %} </code></pre> <p>While this code is easy to write, it suffers from executing a db query for every iteration.</p> <p>One quick solution is called query partitioning. Use 2 queries and python to populate the reverse relationship as efficiently as possible without going to SQL.</p> <pre><code>widgets = Widget.objects.filter(...) finished_widget_map = dict( [(x['thing__id'], x['created']) for x in Finished_Widget.objects.filter(thing__in=widgets, user=request.user).values_list('thing__id', 'created').order_by('created')]) # this ensures we only select what we need, thing__id and the created column # ordering by created will ensure only the last (latest) will appear in our dictionary for widget in widgets: widget.latest_finished_widget_created = finished_widget_map.get(widget.id, 'No Widget') {% for widget in widgets %} {{ widget.name }} {{ widget.latest_finished_widget_created }} {% endfor %} </code></pre> <p>There are always tradeoffs though. This could potentially be slow if there are many many Finished_Widgets python is pointlessly trying to populate a dict with.</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.
 

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