Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

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.

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 file, we will write the route for the search

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

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

            # 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')
                context['object_list'] =
            except PageNotAnInteger:
                context['object_list'] =
            except EmptyPage:
                context['object_list'] =

        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.


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()


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 %}
    {% if object_list %}
        {% for object in object_list %}
                <a href="{{ object.get_absolute_url }}">
                    <h2>{{ object.itle }}</h2>
                {{ object.content|safe }}
                <p><a class="btn btn-default btn-sm" href="{{ object.get_absolute_url }}">Read more</a></p>
        {% 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


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

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


Only authorized users can post comments.
Please, Log in or Sign up
Jan. 17, 2019, 11:51 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Jan. 17, 2019, 11:49 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
Jan. 17, 2019, 11:13 a.m.

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

  • Result:28points,
  • Rating points-10
Last comments
Jan. 16, 2019, 8:06 a.m.

Заработало. Забыл model->select(); вписать.
Jan. 16, 2019, 8:02 a.m.

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
Jan. 16, 2019, 7:43 a.m.

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

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