[Answer]-How do I query on two incoming models using the Django ORM?

1👍

You can query it directly in the template like this:

<table>
{% for ds in data_streams %}
   <tr>
      <td>
          {% ds.category %}
      </td>
      <td>
          {% for subcat in ds.datastreamsubsategory_set.all %}
               {{subcat.sub_category}}
          {% endfor %}
      </td>
      <td>
          {% for example in ds.datastreamexample_set.all %}
               {{example.example}}
          {% endfor %}
      </td>
{% empty %}
   <tr><td colspan="3">No categories found</td></tr>
{% endfor %}
</table>

I shall let you figure out the formatting yourself.

In the context, just send {'data_streams': data_streams}

Basically, for reverse foreign key relationships, you would do object.lowercasemodelname_set.all() to get the related object queryset.

Read more on lookups that span relationships here

Or you could add a related_name attribute and use that instead of lowercasemodelname_set

You might want to even consider prefetch_related option if you want to reduce the number of queries on the database

Leave a comment