Note that there are some explanatory texts on larger screens.

plurals
  1. POQuerying data from a specific related object in Django template
    primarykey
    data
    text
    <p>I'm trying to use Django to display a table of information from across several models and I'm uncertain what the best practices for doing so are. Here's a stripped down version of my models.py:</p> <pre><code>from django.contrib.auth.models import User class Widget(models.Model): name = models.CharField(max_length=50) pass class Finished_Widget(models.Model): user = models.ForeignKey(User) thing = models.ForeignKey(Thing) created = models.DateTimeField(editable=False) </code></pre> <p>It's a pretty simple setup with the User and the Widget being connected through an unknown number of Finished_Widget objects. What I'd like to show in my html is a list of instances of the Widget names and the date of the most recent finished widget. Obviously the below code doesn't work, but hopefully it'll illustrate what data I'm looking to have output.</p> <pre><code>{% for widget in widget_list %} &lt;p&gt;{{ widget.name }}&lt;/p&gt; &lt;p&gt;{{ widget__Finished_Widget.latest.created }}&lt;/p&gt; {% endfor %} </code></pre> <p>I've thought about a number of different approaches to the problem, including:</p> <ul> <li>appending the desired date as an additional attribute via the view</li> <li>creating a dictionary in the view and calling that in the template</li> <li>the ManyToManyField using the 'through' argument</li> <li>adding meta to the Widget calling to the created date of the latest Finished_Widget</li> </ul> <p>Unfortunately I haven't been able to make any of these work, and I'm not sure which, if any, are even on the right path.</p> <p>Note: I've found quite a few variations on this problem on SO already which makes this pretty close to a dupe, but they don't seem to have helped me much because of the need to narrow down the Finished_Widget list to those matching the user ID, matching the Widget ID, <strong>and</strong> only the latest one.</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. 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