D
D
Dzhemchik2020-02-07 00:06:14
Django
Dzhemchik, 2020-02-07 00:06:14

How to dynamically display query_set() in one template?

I don't really understand how to properly override get_query_set(). It is necessary to display all categories on the main page, but when the user clicks on the link to the category of interest, display only the elements included in this category. The tables are linked. I need help, I've been trying to implement for a long time. I looked at the dock , but to no avail. Below code:

#models

class Category(models.Model):
    name = models.CharField(verbose_name='Категория', max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True,
                            unique=True)
...
    def get_absolute_url(self):
        return reverse('core:product_list_by_categories',
                       args=[self.slug])


class Product(models.Model):
    vencode = models.CharField('Артикул', max_length=100, primary_key=True)
    slug = models.SlugField(max_length=100, db_index=True)
    describe = models.TextField('Описание', blank=True)
    price = models.DecimalField('Цена', max_digits=20, decimal_places=2)
    category = models.ForeignKey('Category', related_name='products', on_delete=models.SET_NULL,
                               null=True, verbose_name='Категория')
    available = models.BooleanField(default=True)

    class Meta:
        index_together = (('vencode', 'slug'),)

    def get_absolute_url(self):
        return reverse('core:product_detail', args=[str(self.slug)])

    def save(self, *args, **kwargs):
        self.slug = slugify(self.vencode, allow_unicode=True)
        super(Product, self).save(*args, **kwargs)

# urls
app_name = 'core'

urlpatterns = [
    path('', views.ProductView.as_view(), name='products'),
    path('categories/<slug:category_slug>/',
            views.ProductView.as_view(),
            name='product_list_by_categories'),]

#views

class ProductView(generic.ListView):
    ...
    categories = Category.objects.

    def get_queryset(self, category_slug=None):
        self.category = None
        if category_slug:
            self.category = get_object_or_404(Category, slug=category_slug)
            return Product.objects.filter(category=self.category)
        return Product.objects.filter(available=True)

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        context['Products'] = self.form_class
        context['categories'] = self.categories
        #context['category'] = self.category
        return context

#html
<h3>Categories</h3>

          <li {% if not category %}class="selected"{% endif %}>
                    <a href="{{ categories.get_absolute_url }}">Все категории</a>
          </li>
          {% for c in categories %}
          <li {% if categories.slug == c.slug %}class="selected"{% endif %}>
                    <a href="{{ c.get_absolute_url }}">{{ c.name }}</a>
          </li>
          {% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-07
@dzhem911

The method get_querysetcan have only one argument - self. In order to get inside this method, category_slugyou need to refer to self.kwargs- this dictionary contains all the variables that you defined in urls. So your code should look something like this:

def get_queryset(self):
    self.category = None
    if 'category_slug' in self.kwargs:
        self.category = get_object_or_404(Category, slug=self.kwargs['category_slug'])
        return Product.objects.filter(category=self.category)
    return Product.objects.filter(available=True)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question