Django model.objects.all()查询集不显示内容-如何修复?

时间:2019-02-10 08:06:11

标签: django django-views django-queryset

我正在学习Django,并尝试设置一些动态页面。我已将url映射到/ restaurants和/ restaurants / mexican,但是我的html内容块未显示任何查询集。下面的代码:

views.py

def restaurantListView(request):
    template_name = 'restaurants/restaurants_list.html'
    queryset = Restaurant.objects.all()
    context = {
        "objectList": queryset
    }
    return render(request, template_name, context)

class RestaurantListView(ListView):
    queryset = Restaurant.objects.all()
    template_name = 'restaurants/restaurants_list.html'

class MexicanRestaurantListView(ListView):
    queryset = Restaurant.objects.filter(category__iexact='mexican')
    template_name = 'restaurants/restaurants_list.html'

class AsianFusionRestaurantListView(ListView):
    queryset = Restaurant.objects.filter(category__iexact='asian fusion')
    template_name = 'restaurants/restaurants_list.html'

urls.py

from restaurants.views import (
    restaurantListView, 
    RestaurantListView, 
    MexicanRestaurantListView, 
    AsianFusionRestaurantListView,
    )

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='home.html')),
    path('restaurants/', RestaurantListView.as_view()),
    path('restaurants/mexican/', MexicanRestaurantListView.as_view()),
    path('restaurants/asian/', AsianFusionRestaurantListView.as_view()),
    path('about/', TemplateView.as_view(template_name='about.html')),
    path('contact/', TemplateView.as_view(template_name='contact.html')),
]

restaurants_list.html

{% extends "base.html" %}

{% block head_title %} Restaurants || {{ block.super }} {% endblock %}

{% block content %}

<h1>Restaurant List</h1>

<ul>
    {% for obj in objectList %}
        <li>{{ obj.name }} | {{ obj.location }}</li>
    {% endfor %}
</ul>

{% endblock content %}

我希望Restaurant.objects.all()的项目显示在restaurant.html的内容块中,但是什么也不显示。 / restaurants /墨西哥路线上的objects.filter()也会发生同样的情况。

2 个答案:

答案 0 :(得分:1)

模板变量应为object_list,而不是objectList

(注意,您当然不需要每种餐厅类型一个视图。而是有一个RestaurantsByType视图,并将该类型作为URL参数。)

答案 1 :(得分:0)

''' 只需在“ category__iexact”中添加一个额外的“ _” '''

class MexicanRestauratListView(ListView):
    queryset = RestaurantLocation.objects.filter(category__iexact='mexican')
    template_name = "restaurants/restaurantlocation_list.html"

class AsianFusionRestauratListView(ListView):
    queryset = RestaurantLocation.objects.filter(category__iexact='asian fusion')
    template_name = "restaurants/restaurantlocation_list.html"