Django: looping through filtered list in template
我有一个 html 模板,我想在模型 (
models.py(缩写为仅显示相关字段)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Subfamily(models.Model): subfamily_name = models.CharField(max_length=200) class Tribe(models.Model): subfamily = models.ForeignKey(Subfamily, on_delete=models.SET_NULL, null=True) tribe_name = models.CharField(max_length=200) class Genus(models.Model): tribe = models.ForeignKey(Tribe, on_delete=models.SET_NULL, null=True) genus_name = models.CharField(max_length=200) class Species(models.Model): genus = models.ForeignKey(Genus, on_delete=models.SET_NULL, null=True) species_name = models.CharField(max_length=200) species_page = models.OneToOneField('SpeciesPage', on_delete=models.SET_NULL, null=True) class SpeciesPage(models.Model): title = models.CharField(max_length=100, primary_key=True) species_name = models.OneToOneField(Species, on_delete=models.SET_NULL, null=True) |
views.py
1 2 3 4 5 6 7 8 9 10 11 12 | class SpeciesPageListView(generic.ListView): model = SpeciesPage template_name = 'speciespage_list.html' def show(request): pierinae_pages = SpeciesPage.objects.filter(species_name__genus__tribe__subfamily__subfamily_name="Pierinae") context = { 'pierinae_pages': pierinae_pages, } return render(request, 'speciespage_list.html', context=context) |
speciespage_list.html
1 2 3 4 5 6 7 8 | ... {% for speciespage in pierinae_pages %} <tr> <td>{{ speciespage.title }}</td> ... </tr> {% endfor %} ... |
我从这里使用了以下答案来尝试解决我的问题:
- 无法在 Django 模板 html 中使用过滤器
- 迭代模板中的模型实例字段名称和值
任何帮助将不胜感激。谢谢!
几件事:
您不想将
我认为您可以简化您的
1 2 3 4 5 | class SpeciesPageListView(generic.ListView): model = SpeciesPage template_name = 'speciespage_list.html' queryset = SpeciesPage.objects.filter(species_name__genus__tribe__subfamily__subfamily_name="Pierinae") context_object_name = 'pierinae_pages' |
然后在 urls.py:
1 2 3 | urlpatterns = [ path('', views.SpeciesPageListView.as_view(), name='index'), ] |