Note that there are some explanatory texts on larger screens.

plurals
  1. POGet filtered object from a ForeignKey relation in django template
    text
    copied!<p>I am having a problem with <a href="https://stackoverflow.com/a/224003/688161">djangos design choice</a> not to allow model filtering in templates. Actually, I do understand its sense and I do not really want to break it, but currently I cannot see what's the best or usual method to circumvent my situation.</p> <p>I am having a model <code>Task</code> with a foreign key <code>user_solutions</code> to another model <code>Solution</code>. Now I am iterating over all Tasks and if the user already has a solution for this task, I want to display both a tick and the link to his solution. Somewhat like this:</p> <pre><code>{% for task in tasks %} {{ task.title }} {% if task.user_solutions.filter(author=author).count() &gt; 0 %} Tick! {{ task.user_solutions.get(author=author).get_absolute_url }} {% endif %} {% endfor %} </code></pre> <p>Yes, it looks cruel querying the database two times for the same information and django template does not accept it like this (correctly).</p> <p>However, the other approaches to not seem to work either:</p> <ul> <li>I cannot add a method <code>Task.get_current_user_solution()</code>, because in the model I do not know which user is logged in</li> <li>I cannot add a method <code>Task.get_user_solution(user)</code>, because I cannot pass arguments through the template</li> <li>I cannot query information in the view and save it into a dictionary <code>current_users_solutions</code> (with <code>Task.id</code> as index), because in the template, I cannot use combined variables to access dictionaries (and the index to access it would of course be <code>task.id</code>)</li> </ul> <p>So what else is there I can do? From the linked article I can only see that I could add a new template tag to allow querying from the template, but as said, I actually would like to follow djangos design principle if possible.</p>
 

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