Python 如何显示存储在QuerySet对象中的模型的属性?

Python 如何显示存储在QuerySet对象中的模型的属性?,python,django,django-queryset,Python,Django,Django Queryset,我的django应用程序有一个简单的模型,我创建了3个实例,每个实例都有title和description属性,如何使用这些属性在html模板中显示 models.py: from django.db import models class Solution(models.Model): title = models.CharField(max_length=200, help_text='Enter a title of solution') description = mo

我的django应用程序有一个简单的模型,我创建了3个实例,每个实例都有title和description属性,如何使用这些属性在html模板中显示

models.py:

from django.db import models

class Solution(models.Model):
    title = models.CharField(max_length=200, help_text='Enter a title of solution')
    description = models.TextField(max_length=1000, help_text='Enter a description of solution',)

    def __str__(self):
        return self.title
views.py:

from django.shortcuts import render
from .models import Solution
from django.views import generic

def index(request):
    solutions = Solution.objects.all()
    return render(request, "main/index.html", {'solutions': solutions})
我需要在html文件中执行以下操作:

<div class="content">
  <h3>{{ solution.title }}</h3>

{{solution.title}}

如果只需要第一个对象,则必须编辑查询,请按如下方式尝试:

Views.py

from django.shortcuts import render
from .models import Solution
from django.views import generic

def index(request):
    solutions = Solution.objects.first()
    return render(request, "main/index.html", {'solutions': solutions})
模板

{{ solutions.title }}
如果不想更改查询,还可以在模板中使用以获取第一个对象:

{{ solutions|first }}

循环不合适,我只需要给定h3中的一个模型,例如,只有QuerySet中第一个对象的标题。然后你需要更改你的查询,我编辑了我的答案:)是的,很好,它可以正常工作,但现在的问题是,当我需要它时,我如何才能到达2、3、10等等元素?很好:)你能接受我的答案吗?我以为那是类似于“{{solutions.1}},{{{{solutions.2}}”之类的东西,但我不确定。我马上给你查一下。是的,你应该这样做