Home > other >  Django Queryset to search for article title
Django Queryset to search for article title

Time:11-25

I aim to search for the article title using a query set, I am following this 'basic filtering' guide however it doesn't work for me.

terminal traceback-

AttributeError: 'DeferredAttribute' object has no attribute 'filter'

views.py

class SearchResultsView(ListView):
    model = Article
    template_name = 'search_results.html'
    queryset = Article.title.filter(name__icontains='1st')

I tried using queryset = Article.objects.filter(name__icontains='1st') however this resulted in the below which is why I used 'title' rather than 'objects'

File "/Users/Lucas/Python/Projects/news/.venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1677, in names_to_path
    raise FieldError(
django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: author, author_id, body, comment, date, id, title

models.py

class Article(models.Model):
    title = models.CharField(max_length=225)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("article_detail", kwargs={"pk": self.pk})

I looked at this but can't get it to work. Also tried the documentation.

If i remove the query set line at the bottom of the class the search function returns all of the values as per the below .html file. Which displays all the article content but without any filters of course.

search_results.html

<ul>
  {% for article in article_list %}
    <li>
      {{ article.title }}, {{ article.body }} {{ article.date }}{{ article.author }}
    </li>
  {% endfor %}
</ul>

Am I missing something from the model perhaps? Thanks.

CodePudding user response:

Try:

queryset = Article.objects.filter(title__icontains='1st') in SearchResultsView

The error mentions that you do not have name field. Since you are using title field, you need to use that instead.

  • Related