为什么Django返回Django对象不是可迭代的错误?

时间:2019-03-06 14:49:16

标签: python django

我得到this错误的原因是什么?

models.py

class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name


class SubCategory(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image_url = models.CharField(default=0, max_length=2000)
    price = models.IntegerField(default=0)

views.py

def category(request, pk):
    categories = Category.objects.get(id=pk)
    subcategories = SubCategory.objects.filter(category=categories)
    return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories})

urls.py

urlpatterns = [
    path('', views.index),
    url(r'^category/(?P<pk>\d+)$', views.category, name='category'),
]

base.html

{% for category in categories %}
<a class="dropdown-item" href="{% url 'category' pk=category.id %}">{{ category.name }}</a>
{% endfor %}

3 个答案:

答案 0 :(得分:2)

get返回一个模型实例,而不是一个查询集(尽管您误导了变量名):

categories = Category.objects.get(id=pk)  # instance, not queryset!

因此:

{% for category in categories %}  # instance cannot be looped over!

产生您遇到的错误。

答案 1 :(得分:0)

您正试图在下面的文件中仅获取一个Category对象。

views.py

def category(request, pk):
        categories = Category.objects.get(id=pk) # Here you trying to get category
        subcategories = SubCategory.objects.filter(category=categories)
        return render(request, 'category.html', {
            'categories': categories, # categories is single object not iterable
            'subcategories': subcategories})

对于解决方案,您可以将categories = Category.objects.filter(id=pk)设置为您的 views.py 或更新您的 html模板

答案 2 :(得分:0)

因为我的错误与queryset有关。这是什么意思 ?数组。并且每个数组都有其索引,因此,在此示例中,我们的“类别”是一个数组,我们必须将其第一个([0])索引分配给一个类别:

def category(request, pk):
        categories = Category.objects.get(id=pk)
        subcategories = SubCategory.objects.filter(category=categories[0])
        return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories})