Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
g

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

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
ГК
March 20, 2019, 9:01 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:0points,
  • Rating points-10
ГК
March 20, 2019, 8:46 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
MU
March 20, 2019, 3:43 p.m.
Maciej Urmański

It's possible to simply add vote option for non logged users?
March 20, 2019, 9:45 a.m.
Евгений Легоцкой

Добрый день. Поппробуйте домен localhost, а url соответственно http://localhost Возможно, потребуется указать порт. Например, так http://localhost:8000
March 19, 2019, 12:57 p.m.
AlexanderBardin

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)
March 16, 2019, 1:55 p.m.
Дмитрий

Спасибо за статью. Давно итересует следующий вопрос: с помощью переменных QMAKE_TARGET_COMPANYQMAKE_TARGET_PRODUCTQMAKE_TARGET_DESCRIPTIONможно задать свойства компилируемой программы, о...
JS
March 12, 2019, 10:19 a.m.
Jean Stefanovich

Большое спасибо за разъяснения!
Now discuss on the forum
March 20, 2019, 12:26 p.m.
Евгений Легоцкой

Лучше стараться избегать этого. Нормального механизма нет. Я просто выдёргиваю из бэкенда перевёденные куски шаблона, если нужно что-то задействовать в JS.
March 17, 2019, 10:47 p.m.
Евгений Легоцкой

Добрый день. Вот, нашлось у меня немного времени. Делается это через шаблон проектирования наблюдатель. GraphKS_mfvSlup.zip
ЧГ
March 15, 2019, 9:52 p.m.
Чарльз Грин

спасибо, попробую, отпишусь
m
March 15, 2019, 7:41 p.m.
mihamuz

Сори догадался)
n
March 12, 2019, 4:57 p.m.
newbie.works.with.QT

Большооооое спасибо!!!!!Не передать как я вам благодарен, спасибо что всегда отзываетесь.Теперь я смогу продолжить работу в QT!!! (пробую писать бота (Я как вы могли догадаться немного не пр...
Join us in social networks

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