【问题标题】:Unable to display QuerySet in Django view无法在 Django 视图中显示 QuerySet
【发布时间】:2019-11-11 10:10:58
【问题描述】:

我试图使用下面的方法显示一个 QuerySet, Passing Django Queryset in Views to Template

我可以使用 get() 方法显示单个对象,但是当我尝试返回餐厅表中的所有数据时,它会以空白页的形式返回。

一流餐厅

class Restaurant(models.Model):
    restId = models.AutoField(db_column='restId', primary_key=True)
    restName = models.TextField(db_column='restName')
    phone = models.IntegerField()
    address = models.TextField()
    ratings = models.DecimalField(max_digits=2, decimal_places=1)
    cuisine = models.TextField()
    region = models.TextField()
    #image = models.ImageField()
    last_modify_date = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        managed = True
        db_table = "restaurant"

views.py

def index_view(request):
    rest_list = Restaurant.objects.all()
    context = {
        'rest_list': rest_list
    }
    return render(request, 'index.html', context)

index.html

    <h1>Index</h1>
    {% for rest in rest_List %}
        {{ rest.restId }}
        {{ rest.restName }}
    {%  endfor %}

【问题讨论】:

  • 当您尝试时,rest_list 打印或返回什么?
  • 你打错了,是rest_listl,不是L)。

标签: python django


【解决方案1】:

用以下代码替换“index.html”代码:您的错误是“rest_list”中的语法错误。

<h1>Index</h1>
{% for rest in rest_list %}
    {{ rest.restId }}
    {{ rest.restName }}
{%  endfor %}

Python 是一种区分大小写的语言。

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2019-12-29
    • 1970-01-01
    • 2019-05-29
    • 2015-04-02
    • 1970-01-01
    相关资源
    最近更新 更多