如何构建查询以获取具有特定作者的项目中所有任务的输出?在我的模板中,我想迭代所有项目并显示父项目下的所有任务。
{% for p in projects %}
add project html
{% for t in projects.tasks %}
add task html
{% endfor %}
{% endfor %}
型号:
class Project(models.Model):
projectname_text = models.CharField('Projectname', unique=True, max_length=200)
class Task(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE,)
task_text = models.CharField(max_length=200)
author = models.ForeignKey(User, null=True, blank=True, related_name='author')
我希望有人能帮助我:)。
答案 0 :(得分:1)
我建议您修改project
模型上的Task
字段,如下所示:
class Task(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE,
related_name='tasks')
# ...
这将允许您通过project.tasks.all()
访问特定项目的所有任务。
您还需要稍微修改您的模板,因为您当前指的是projects
,您应该引用p
,而您需要循环p.tasks.all
而不仅仅是p.tasks
{% for p in projects %}
add project html
{% for t in p.tasks.all %}
add task html
{% endfor %}
{% endfor %}
。
projects
您需要确保 <header> <!--Header -->
<!-- Top Navigation -->
<nav>
<ul class="clearfix">
<li><a class="what" href="#">What ?</a></li>
<li><a class="new" href="#">+ New Game</a></li>
</ul>
</nav>
<!-- Modal Information Box -->
<div class="overlay" id="modal">
<div class="content">
<h3>What do I do?</h3>
<div>
<p>This is a Hot or Cold Number Guessing Game. The game goes like this: </p>
<ul>
<li>1. I pick a <strong>random secret number</strong> between 1 to 100 and keep it hidden.</li>
<li>2. You need to <strong>guess</strong> until you can find the hidden secret number.</li>
<li>3. You will <strong>get feedback</strong> on how close ("hot") or far ("cold") your guess is.</li>
</ul>
<p>So, Are you ready?</p>
<a class="close" href="#">Got It!</a>
</div>
</div>
</div>
<!-- logo text -->
<h1>HOT or COLD</h1>
</header>
<section class="game"> <!-- Guessing Section -->
<h2 id="feedback">Make your Guess!</h2>
<form>
<input type="text" name="userGuess" id="userGuess" class="text" maxlength="3" autocomplete="off" placeholder="Enter your Guess" required/>
<input type="submit" id="guessButton" class="button" name="submit" value="Guess"/>
</form>
<p>Guess #<span id="count">0</span>!</p>
<ul id="guessList" class="guessBox clearfix">
</ul>
</section>
<!-- JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
在您的视图中传递给您的模板的上下文中。