How to query data within a certain period of time with Vue front-end and Django back-end

How to query data within a certain period of time with Vue front-end and Django back-end

Preface

During the development process, you will often encounter functions such as filtering queries, such as querying data within a certain time period instead of all data.

In this way, we need to send the time period parameters to the backend, and then process the query on the backend.

Here we use a simple example of Django backend and Vue frontend to record the general implementation.

Backend database

Here are some simple data. The important thing is the date. We need to filter and return it to the front end based on the date.

models.py

class CountDownSign(models.Model):
 name = models.CharField(max_length=1000) 
 date = models.DateField() 
 sign = models.CharField(max_length=200) 

serializers.py

The drf framework is introduced here, but the idea of ​​filtering queries has nothing to do with this framework.

class CountDownModelSerializer(serializers.ModelSerializer):
 class Meta:
 model = CountDownSign
 fields = '__all__'

 def create(self, validated_data):
 return CountDownSign.objects.create(**validated_data)

 def update(self, instance, validated_data):
 instance.name = validated_data.get('name', instance.name)
 instance.date = validated_data.get('date', instance.date)
 instance.sign = validated_data.get('sign', instance.sign)
 instance.save()
 return instance

views.py

Provides an interface for filtering queries. Get the start and end dates delivered by the front end. The core code is as follows

obj = models.CountDownSign.objects.filter(date__range=(start, end))
class CountDownViewSet(ModelViewSet):
 parser_classes = [JSONParser, FormParser]
 """ViewSet"""
 queryset = models.CountDownSign.objects.all()
 serializer_class = CountDownModelSerializer
 # Search search_fields = ('id', 'name', 'sign', 'date')
 
 @action(methods=['post'], detail=False)
 def getSE(self, request, *args, **kwargs):
 start = request.data.get('start', None)
 end = request.data.get('end', None)
 if start and end:
  obj = models.CountDownSign.objects.filter(date__range=(start, end))

  if obj:
  ser = CountDownModelSerializer(instance=obj, many=True)
  print(ser.data)
  return JsonResponse({
   'code': '200',
   'msg': 'Get data successfully',
   'data': ser.data
  })
  else:
  return JsonResponse({
   'code': '1002',
   'msg': 'Get failed',
  })
 else:
  return Response(status=status.HTTP_204_NO_CONTENT)

Front-end interface

Here are two date-pickers for receiving the start and end time, and binding events for the search.

 <div class="datePicker">
 <div class="block" style="float: left">
 <el-date-picker
  v-model="value1"
  type="datetime"
  value-format="yyyy-MM-dd"
  placeholder="Please select a start date">
 </el-date-picker>
 </div>
 <div class="block" style="float: left; margin-left: 20px;">
 <el-date-picker
  v-model="value2"
  type="datetime"
  value-format="yyyy-MM-dd"
  placeholder="Please select a deadline">
 </el-date-picker>
 </div>
 <el-button round style="float: left; margin-left: 20px;" @click="searchC">Search</el-button>
 </div>

data.js

Implemented interface functions

export function searchCountDown(start, end) {
 return request({
 url: 'countDown/getSE/',
 method: 'post',
 data: {
  start: start,
  end: end
 }
 })
}

Click event implementation

Determine the legitimacy of the input and accept the data for data binding display

searchC() {
 console.log(this.value1);
 console.log(this.value2);
 if (this.value1 < this.value2) {
 searchCountDown(this.value1, this.value2).then(res => {
  console.log(res.data);
  this.searchRes = res.data;
 })
 } else {
 this.$message.error("Time range error");
 }
 },

Data display

 <div class="article">
 <ul>
 <li v-for="(item,index) in searchRes">
  <div class="ui grid" style="width: 100%;height: 60px;">
  <div class="four wide column"><span>{{ item.name }}</span></div>
  <div class="four wide column"><span>{{ item.date }}</span></div>
  <div class="four wide column"><span>{{ item.sign }}</span></div>
  <div class="four wide column">
  <el-button type="danger" icon="el-icon-delete" circle @click="deleteC(item.id)"></el-button>
  <el-button type="primary" icon="el-icon-edit" circle></el-button>
  </div>
  </div>
  <div class="ui divider"></div>
 </li>
 </ul>

Operation Results

It can be seen that the returned data are all within the time range. Here, the data returned at 0:00 on February 25th is actually the data of February 5th. Because the data is formatted, the data of the 25th is also returned.

Summarize

This is the end of this article about how to query data within a certain period of time with Vue front-end and Django back-end. For more relevant Vue and Django data query content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Perfect solution to the conflict between Django and Vue syntax
  • Example of building a front-end and back-end separation project with Django+Vue.js
  • How to implement data interaction between Django and Vue
  • Methods and steps for data interaction using Django and Vue
  • Django+Vue cross-domain environment configuration detailed explanation

<<:  MySQL NULL data conversion method (must read)

>>:  Example of how to configure multiple virtual hosts in nginx

Recommend

Detailed explanation of Nginx current limiting configuration

This article uses examples to explain the Nginx c...

Small program to implement a simple calculator

This article example shares the specific code of ...

Solve the problem of garbled Chinese characters in Mysql5.7

When using MySQL 5.7, you will find that garbled ...

Vue uses the Element el-upload component to step on the pit

Table of contents 1. Basic Use 2. Image quantity ...

Summary of things to pay attention to in the footer of a web page

Lots of links You’ve no doubt seen a lot of sites ...

HTML table tag tutorial (44): table header tag

<br />In order to clearly distinguish the ta...

XHTML tags have a closing tag

<br />Original link: http://www.dudo.org/art...

Calendar effect based on jQuery

This article example shares the specific code of ...

Example of using Docker Swarm to build a distributed crawler cluster

During the crawler development process, you must ...

mysql5.7 remote access settings

Setting up remote access in mysql5.7 is not like ...

Detailed explanation of crontab scheduled execution command under Linux

In LINUX, periodic tasks are usually handled by t...

A detailed account of the process of climbing a pit of Docker deployment service

First time writing. Allow me to introduce myself....

CSS to achieve scrolling image bar example code

On some websites, you can often see some pictures...

Causes and solutions for MySQL deadlock

The database, like the operating system, is a sha...