Krystian Kazimierczak
Krystian Kazimierczak

Reputation: 582

Django QuerySet object has no attribute 'objects

I have problem with show product in category. (Products are show but when i click on category (tshirt) i have this problem AttributeError at /man/tshirt/ 'QuerySet' object has no attribute 'objects

views.py

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(section='man', available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.objects.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products})

urls.py

 urlpatterns = [
    url(r'^$', views.main, name='main'),
    url(r'^man/$', views.product_list, name='product_list'),
    url(r'^man/(?P<category_slug>[-\w]+)/$',
        views.product_list,
        name='product_list_by_category'),


]

models.py

class Category(models.Model):
    name = models.CharField(max_length=200,
                            db_index=True)
    slug = models.SlugField(max_length=200,
                            db_index=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                       args=[self.slug])

list.html

{% extends "shop/base.html" %}
{% load static %}

{% block title %}VPW{% endblock %}

{% block content %}
<ul>
    {% for c in categories %}
    <li>
        <a href="{{ c.get_absolute_url }}">{{c.name}}</a>
    </li>
    {% endfor %}
</ul>

    {% for product in products %}
     {{ product.name }}
    {% endfor %}
{% endblock %}

Upvotes: 12

Views: 32847

Answers (1)

Oleksandr Dashkov
Oleksandr Dashkov

Reputation: 2838

You should change

products = products.objects.filter(category=category)

to

products = products.filter(category=category)

In short, you've already queried data at the objects level, thus the .objects identifier is no longer necessary or valid at this point in the code.

You can find more info here.

Upvotes: 25

Related Questions