Quick Code
Published in

Quick Code

SearchFilter using Django and Vue.js

The post is in continuation with my previous post where I explained to make CRUD api’s using the vue.js 2.x and Django 2.0.2, PLEASE READ THAT POST FIRST THEN GO THOUGH THIS POST

In this tutorial you will learn how to make a SearchFilter using Django and Vue.js

Just follow the steps to make a SearchFilter

  • Add a search filter tag in the django rest framework viewset
  • Mentioning the fields on which search should perform
  • Understanding the search api
  • Integrating the search api with the vue.js

Adding a search filter tag in the django rest framework

from rest_framework import viewsets, filters
from .models import Article
from .serializers import ArticleSerializer
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('article_id', 'article_heading','article_body')

Observe the highlighted additions to the previous code, first of all we have imported the filters and then mention the SearchFilter in the filter backends.

Mentioning the fields on which search should perform

from rest_framework import viewsets, filters
from .models import Article
from .serializers import ArticleSerializer
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('article_id', 'article_heading','article_body')

Here we have mentioned the fields on which the search has to performed, in-fact here you can add the foreign key fields also like if category is a foreign key and it contains a field called ‘name’ then you can add like category__name search will also perform on that field too.

Understanding the search api

Now the important part how do you call this api to get the search results. Have a look at the routers file in the myproject folder

from rest_framework import routers
from article.viewsets import ArticleViewSet
router = routers.DefaultRouter()router.register(r'article', ArticleViewSet)

In the last post we are making api calls at the api endpoint /api/article the same we do for search but just add a search param to the get request like /api/article?search=search_term nothing new and we get the refined results.

Integrating the search api with vue.js

First of all the search box along the add article button

<h1>List of Articles
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addArticleModal">ADD ARTICLE</button>
</h1>
&emsp;
<div class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" v-model="search_term" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" v-on:click.prevent="getArticles()">Search</button>
</div>

The search input if mapped with the search_term variable in the vue instance and the search button will run the modified getArticles() function

Modification of the getArticles function to add the search term

      data: {
articles: [],
loading: true,
currentArticle: {},
message: null,
newArticle: { 'article_heading': null, 'article_body': null },
search_term: '',
},
mounted: function() {
this.getArticles();
},
methods: {
getArticles: function() {
let api_url = '/api/article/';
if(this.search_term!==''||this.search_term!==null) {
api_url = `/api/article/?search=${this.search_term}`
}

this.loading = true;
this.$http.get(api_url)
.then((response) => {
this.articles = response.data;
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},

First of all there is a search term parameter in the initial data bag, to handle the changes in the search term, next the modification in the getArticles function we have updated the getArticles function by adding checking whether there is a search term or not if there is a search term then append to the url otherwise not.

Now, you are done just hit the main step

python manage.py runserver

and see your app working

Please refer to https://github.com/ShubhamBansal1997/crud-app-vuejs-django to see the code and this webapp is active here https://vue-django-crud-heroku.herokuapp.com . If you found any error please do mention in the comments.

Made with

Tips Are Appreciated! 💰 😉

My Bitcoin address: bc1qysxlz0p9nlcyndeysqltdhelwpdhurglgxz96x

My Ethereum address: 0x42c98e296B27228d9ee84e519BEC8eE0d09cad30

--

--

--

Find the best tutorials and courses for the web, mobile, chatbot, AR/VR development, database management, data science, web design and cryptocurrency. Practice in JavaScript, Java, Python, R, Android, Swift, Objective-C, React, Node Js, Ember, C++, SQL & more.

Recommended from Medium

React vs Angular in my opinion:

Set Expiry Time (TTL) for LocalStorage With Javascript

Easy GraphQL Union Types With Apollo Client V2

Fetching, Fetched, and Fetch Error Is Not Enough

Taming huge collections of DOM nodes

Handle Integration and Production Deployments for Nuxt.js Apps

Uploading an Image to Firebase Cloud Storage and returning URL with Express / Nodejs

React Native Tutorials -2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shubham Bansal

Shubham Bansal

Full Stack Engineer | Freelancer | Web D | Scalability | Blockchain | DevOps | AI | ML | IoT | Another random writer | Foodie

More from Medium

Create a Modern Application with Django and Vue — Part Four

Django Dashboard Material — Open-Source Starter

Django Dashboard Material — Open-Source Seed Project

Containerized Django PostgreSQL Application

Getting started with Django Web Framework and Docker