我有一个html模板,我想在其中循环浏览模型(def main():
# Create an instance of Car
my_car = Car("2008", "Honda Accord")
print("my_car after instantiating:\n", my_car)
my_car.setSpeed(2)
print("my_car after my_car.setSpeed(2):\n", my_car)
# Accelerate 5 times
print ("car is accelerating: ")
for i in range(5):
#my_car.accelerate()
print ("Current speed: ", my_car.getSpeed())
print()
# Brake 7 times
print ("car is braking: ")
for i in range(7):
#my_car.brake()
print ("Current speed: ", my_car.getSpeed())
print("my_car values at program end:\n", my_car)
main()
)中的对象,这些对象由某个字段值(SpeciesPage
)过滤并显示在列表中。筛选的结果跨越多个外键关系。最终,我希望模板循环并在单独的列表中显示多个过滤的结果,但是我无法获得任何内容来渲染一个过滤的列表的循环。我觉得我想要完成的事情应该很简单。
models.py(缩写为仅显示相关字段)
subfamily_name="Pierinae"
views.py
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)
speciespage_list.html
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)
为了解决我的问题,我从这里使用了以下答案:
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
事物的结合:
您不想将OneToOneField
和Species
都指向SpeciesPage
。 (有关详细信息,请参见https://docs.djangoproject.com/en/2.2/topics/db/examples/one_to_one/)
我认为您可以简化ListView
以获得所需的输出:
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中:
urlpatterns = [
path('', views.SpeciesPageListView.as_view(), name='index'),
]