如何反向查询ManytoMany Django
how reverse query ManytoMany Django
我有这两个模型,我想在我的页面中显示带有特定任务的项目。这些是我的模型:
class Project (models.Model):
name = models.CharField(verbose_name="Project name", max_length=25)
tasks = models.ManyToManyField(Task, verbose_name="tasksInProject", blank=True,
related_name="projects+")
class Task(models.Model):
name = models.CharField(verbose_name="Task", max_length=50)
我称这个视图为:
class TaskToProjectFilterView(DetailView):
model = Task
template_name = "vivs/task_filter.html"
context_object_name = "task_filter"
这是我的 html 模板:
<h4>filter : {{ task_filter }} </h4>
<h4>projects :
{% for element in task_filter.projects.all %}
{{ element }}
{% endfor %}
</h4>
此代码显示 {{ task_filter }}
但不显示 {{ task_filter.projects.all }}
的列表。
你能帮帮我吗?我不明白我的错误。谢谢!
如 schwobaseggl 所述,删除 +
标志,它应该可以按预期工作,使用:
{% for element in task_filter.projects.all %}
来自Django Docs:
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model:
我有这两个模型,我想在我的页面中显示带有特定任务的项目。这些是我的模型:
class Project (models.Model):
name = models.CharField(verbose_name="Project name", max_length=25)
tasks = models.ManyToManyField(Task, verbose_name="tasksInProject", blank=True,
related_name="projects+")
class Task(models.Model):
name = models.CharField(verbose_name="Task", max_length=50)
我称这个视图为:
class TaskToProjectFilterView(DetailView):
model = Task
template_name = "vivs/task_filter.html"
context_object_name = "task_filter"
这是我的 html 模板:
<h4>filter : {{ task_filter }} </h4>
<h4>projects :
{% for element in task_filter.projects.all %}
{{ element }}
{% endfor %}
</h4>
此代码显示 {{ task_filter }}
但不显示 {{ task_filter.projects.all }}
的列表。
你能帮帮我吗?我不明白我的错误。谢谢!
如 schwobaseggl 所述,删除 +
标志,它应该可以按预期工作,使用:
{% for element in task_filter.projects.all %}
来自Django Docs:
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'. For example, this will ensure that the User model won’t have a backwards relation to this model: