Django - Tutorial 034. How to do a search on several data models

Search, QuerySet, Django, Model

In previous articles, we considered how to do a search on the site on the site. Namely:

But what if you have more than one type of content. You can have articles, comments, forum and messages on the forum. How then to be?

If you want to do everything yourself, without using third-party libraries, then you will need to do a search on all the necessary models and combine the result. I have done exactly the same on the site.

urls.py

You will need a single View class that will handle the search request.

The important point here is that we will handle get requests so that users can share links with search results.

In the urls.py file, we will write the route for the search

app_name = 'home'
urlpatterns = [
    path('search/', views.SearchView.as_view(), name='search'),
]

views.py

Let's say we have several types of content:

  • Article
  • Comment
  • Topic
  • Post

It is necessary in the view to perform a search on all kinds of content and combine them into one QuerySet and prepare for pagination and issuance

from itertools import chain

from django.shortcuts import render
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views import View

from .models import Article, Comment, Topic, Post


class ESearchView(View):
    template_name = 'search/index.html'

    def get(self, request, *args, **kwargs):
        context = {}

        q = request.GET.get('q')
        if q:
            query_sets = []  # Total QuerySet
            
            # Searching for all models
            query_sets.append(Article.objects.search(query=q))
            query_sets.append(Comment.objects.search(query=q))
            query_sets.append(Topic.objects.search(query=q))
            query_sets.append(Post.objects.search(query=q))

            # and combine results
            final_set = list(chain(*query_sets))
            final_set.sort(key=lambda x: x.pub_date, reverse=True)  # Sorting

            context['last_question'] = '?q=%s' % query_sets

            current_page = Paginator(final_set, 10)

            page = request.GET.get('page')
            try:
                context['object_list'] = current_page.page(page)
            except PageNotAnInteger:
                context['object_list'] = current_page.page(1)
            except EmptyPage:
                context['object_list'] = current_page.page(current_page.num_pages)

        return render(request=request, template_name=self.template_name, context=context)

The nuance of the above code is that we combine all the data models, and also sort them by date. To make this possible, we will use the capabilities of the Python programming language, namely duck typing. Sorting by date became possible because all data models have a publication date field with the same name pub_date .

In general, this is very important when you try to name the fields of data models equally for different data models. This allows you to develop a Django site very flexibly and using duck typing to write templates to display data that does not depend on a particular data type, but rather that depends on the interface that supports your data models.

Also interesting is that the objects of all the data models that are represented in this code have the same search method. This method is not standard. To implement it, you need to write your own model manager and assign it to the objects field.

ArticleManager

Consider the model article manager. We inherit it from the basic model manager and define the search method with the search logic. Similarly, you need to register this method for all models in which the search will be performed.

from django.db import models
from django.db.models import Q

class ArticleManager(models.Manager):
    use_for_related_fields = True

    def search(self, query=None):
        qs = self.get_queryset()
        if query:
            or_lookup = (Q(title__icontains=query) | Q(content__icontains=query))
            qs = qs.filter(or_lookup)

        return qs

Installing the Manager in the Model

class Article(models.Model):
    objects = ArticleManager()

search/index.html

And for a search pattern, you can use a slightly modified template from one of the first articles on organizing a search.

{% load bootstrap34%}
{% block page %}
    <h1>Search</h1>
    {% if object_list %}
        {% for object in object_list %}
            <div>
                <a href="{{ object.get_absolute_url }}">
                    <h2>{{ object.itle }}</h2>
                </a>
                {{ object.content|safe }}
                <p><a class="btn btn-default btn-sm" href="{{ object.get_absolute_url }}">Read more</a></p>
            </div>
        {% endfor %}
        {% bootstrap_pagination object_list url=last_question %}
    {% else %}
        <p>No posts were found for your request <br> Try to repeat the query with a different wording</p>
    {% endif %}
{% endblock %}

I specifically use the depersonalized object parameter in this case, which has no indication of a specific type of content, so it was clear that there could be any content object there. The main thing is that all methods are implemented for all models that are used in this template.

For Django I recommend VDS-hosting TIMEWEB

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate
g

Исправьте код в views.py, пропущен импорт chain из itertools.

Спасибо! Исправил.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m
May 19, 2019, 1:49 a.m.
mahhaki

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
S
May 17, 2019, 1:14 p.m.
SunBro

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
b
May 17, 2019, 4:18 a.m.
banana

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.
Дмитрий

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
P.
May 18, 2019, 2:03 p.m.
PELMYACH .

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
P.
May 14, 2019, 10:33 p.m.
PELMYACH .

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
May 24, 2019, 6:48 a.m.
Евгений Легоцкой

Если там будут только перечисления внутри namespace, то жа, достаточно будет заголовочного файла
May 24, 2019, 6:28 a.m.
Андрей Янкович

работает любой http сервер, и можно использовать обсалютно любой портпример <RemoteRepositories> <Repository> <Url>http://178.124.160.6:3030/A/B&l...;
May 23, 2019, 2:40 p.m.
Михаиллл

Попробовал сделать этот запрос по http и получил json файл. request.setUrl(QUrl("https://jsonplaceholder.typicode.com/todos/1")); Как Вы думаете, почему https не работает и как это и...
May 23, 2019, 10:42 a.m.
Михаиллл

Спасибо, помогло.
May 23, 2019, 6:31 a.m.
Евгений Легоцкой

Для задач и граф-то не нужен. Достаточно будет таблицы в локальной базе данных SQLite, в которой указывается задача, время и т.д. В этом разделе есть примеры по работа с базой д...

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB