A
A
Abai Kerimov2017-06-24 18:29:31
Django
Abai Kerimov, 2017-06-24 18:29:31

How can you filter objects when using select_related()?

I have classes Category and Article. I need to display PUBLISHED articles when selecting them by category.
Code from views.py:

class CategoryDetailView(DetailView):
    model = Category

    def get_context_data(self, **kwargs):
        context = super(CategoryDetailView, self).get_context_data(**kwargs)
        context['article_list'] = Article.objects.select_related()
        return context

And in the template:
{% for article in object.article_set.all %}
        {{ article.title }}
        {{ article.author }}
        {{ article.published }}
{% endfor %}

all articles are displayed by category, but I only need PUBLISHED.
Using
context['article_list'] = Article.objects.select_related().filter(status=1)
nothing happens, unfortunately.
Please, any ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-06-28
@bergsoft

at this point
you are not accessing the article_list variable, you are simply iterating over all the articles that are in the category.
Make your own article manager like this

class ArticleManager(models.Manager):
    def all_published(self):
        return self.get_queryset().filter(status=1)

in the Article model, respectively, add
and then in the template you can call like this
Well, you can remove the redefinition altogether def get_context_data(self, **kwargs):in this case :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question